跳至主要内容

生成单元测试

Copilot Chat 可帮助为函数生成单元测试。

一套完善的单元测试对于任何项目的成功都至关重要。然而,编写这些测试往往耗时且常被忽视。Copilot Chat 可以帮助你自动生成这些测试。

示例情景

假设你有一个在更新数据库前进行数据验证的 Python 函数。你需要编写单元测试,以确保验证能够按预期工作。你可以请 Copilot Chat 为你生成这些测试。

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 提示
/tests Generate unit tests for this function. Validate both success and failure, and include edge cases.

示例回复

注意

以下响应为示例。Copilot Chat 的回复具有不确定性,您可能会得到与此处显示的不同的响应。

如果这是你第一次让 Copilot Chat 生成单元测试,它可能会询问你是否希望为项目配置单元测试。此示例中我们假设你选择拒绝此提议。

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()

延伸阅读

© . This site is unofficial and not affiliated with GitHub, Inc.