# 生成单元测试

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

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

## 示例方案

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

```python id=validate-price
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 copy prompt ref=validate-price
/tests Generate unit tests for this function. Validate both success and failure, and include edge cases.
```

## 示例响应

> \[!NOTE] 以下响应是示例。 Copilot Chat 的回答是不确定的，因此你可能会得到与这里所显示的不同的回答。

如果这是你第一次要求 Copilot Chat 生成单元测试，则可能询问是否要为项目配置单元测试。 在本示例中，我们假设你拒绝了此提议。

Copilot 将提供生成测试的策略，然后自行提供测试。

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

## 延伸阅读

* [GitHub Copilot 对话助手的提示设计](/zh/copilot/concepts/prompting/prompt-engineering)
* [使用 GitHub Copilot 的最佳做法](/zh/copilot/get-started/best-practices)