pFad - Phone/Frame/Anonymizer/Declutterfier! Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

URL: http://docs.github.com/zh/copilot/tutorials/copilot-chat-cookbook/testing-code/generate-unit-tests

ontent="copilot" data-next-head=""/>
Skip to main content

生成单元测试

Copilot对话 可帮助生成函数的单元测试。

本文内容

一套好的单元测试对于任何项目的成功都至关重要。 但是,编写这些测试可能非常耗时,并且经常被忽视。 Copilot对话 可帮助为你生成这些测试。

示例方案

假设你有一个 Python 函数,用于在更新数据库之前验证数据。 你需要创建单元测试,以确保验证按预期方式执行。 你可以让 Copilot对话 为你生成这些测试。

def validate_price(price: float):
  if price <= 0:
    raise ValueError("Price must be greater than 0")
  if price > 1000:
    raise ValueError("Price must be less than or equal to 1000")

示例提示

Copilot prompt
/tests Generate unit tests for this function. Validate both success and failure, and include edge cases.

示例响应

注意

以下响应是示例。 Copilot对话 的回答是不确定的,因此你可能会得到与这里所显示的不同的回答。

如果这是你第一次请求 Copilot对话 生成单元测试,它可能会询问你是否希望为项目配置单元测试。 在本示例中,我们假设你拒绝了此提议。

Copilot 将提供生成测试的策略,然后提供测试本身。

import unittest
from generate_unit_tests import validate_price

class TestValidateProduct(unittest.TestCase):
  def test_price_zero(self):
    with self.assertRaises(ValueError) as context:
      validate_price(0)
    self.assertEqual(str(context.exception), "Price must be greater than 0")

  def test_price_negative(self):
    with self.assertRaises(ValueError) as context:
      validate_price(-10)
    self.assertEqual(str(context.exception), "Price must be greater than 0")

  def test_price_above_limit(self):
    with self.assertRaises(ValueError) as context:
      validate_price(1500)
    self.assertEqual(str(context.exception), "Price must be less than or equal to 1000")

  def test_price_edge_case_zero(self):
    with self.assertRaises(ValueError) as context:
      validate_price(0)
    self.assertEqual(str(context.exception), "Price must be greater than 0")

  def test_price_edge_case_max(self):
    try:
      validate_price(1000)
    except ValueError:
      self.fail("validate_price() raised ValueError unexpectedly!")

if __name__ == '__main__':
  unittest.main()

其他阅读材料

pFad - Phonifier reborn

Pfad - The Proxy pFad © 2024 Your Company Name. All rights reserved.





Check this box to remove all script contents from the fetched content.



Check this box to remove all images from the fetched content.


Check this box to remove all CSS styles from the fetched content.


Check this box to keep images inefficiently compressed and original size.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy