{"meta":{"title":"生成单元测试","intro":"Copilot Chat 可以帮助生成函数的单元测试。","product":"GitHub Copilot","breadcrumbs":[{"href":"/zh/copilot","title":"GitHub Copilot"},{"href":"/zh/copilot/tutorials","title":"教程"},{"href":"/zh/copilot/tutorials/copilot-cookbook","title":"GitHub Copilot 指南"},{"href":"/zh/copilot/tutorials/copilot-cookbook/testing-code","title":"测试代码"},{"href":"/zh/copilot/tutorials/copilot-cookbook/testing-code/generate-unit-tests","title":"生成单元测试"}],"documentType":"article"},"body":"# 生成单元测试\n\nCopilot Chat 可以帮助生成函数的单元测试。\n\n一套好的单元测试对于任何项目的成功都至关重要。 但是，编写这些测试可能非常耗时，并且经常被忽视。\nCopilot Chat 可以帮助你生成这些测试。\n\n## 示例方案\n\n假设你有一个 Python 函数，用于在更新数据库之前验证数据。 你需要创建单元测试，以确保验证按预期方式执行。 你可以让 Copilot Chat 为你生成这些测试。\n\n```python id=validate-price\ndef validate_price(price: float):\n  if price <= 0:\n    raise ValueError(\"Price must be greater than 0\")\n  if price > 1000:\n    raise ValueError(\"Price must be less than or equal to 1000\")\n```\n\n## 示例提示\n\n```copilot copy prompt ref=validate-price\n/tests Generate unit tests for this function. Validate both success and failure, and include edge cases.\n```\n\n## 示例响应\n\n> \\[!NOTE] 以下响应是示例。 Copilot Chat 的回答是不确定的，因此你可能会得到与这里所显示的不同的回答。\n\n如果这是你第一次要求 Copilot Chat 生成单元测试，则可能询问是否要为项目配置单元测试。 在本示例中，我们假设你拒绝了此提议。\n\nCopilot 将提供生成测试的策略，然后自行提供测试。\n\n```python\nimport unittest\nfrom generate_unit_tests import validate_price\n\nclass TestValidateProduct(unittest.TestCase):\n  def test_price_zero(self):\n    with self.assertRaises(ValueError) as context:\n      validate_price(0)\n    self.assertEqual(str(context.exception), \"Price must be greater than 0\")\n\n  def test_price_negative(self):\n    with self.assertRaises(ValueError) as context:\n      validate_price(-10)\n    self.assertEqual(str(context.exception), \"Price must be greater than 0\")\n\n  def test_price_above_limit(self):\n    with self.assertRaises(ValueError) as context:\n      validate_price(1500)\n    self.assertEqual(str(context.exception), \"Price must be less than or equal to 1000\")\n\n  def test_price_edge_case_zero(self):\n    with self.assertRaises(ValueError) as context:\n      validate_price(0)\n    self.assertEqual(str(context.exception), \"Price must be greater than 0\")\n\n  def test_price_edge_case_max(self):\n    try:\n      validate_price(1000)\n    except ValueError:\n      self.fail(\"validate_price() raised ValueError unexpectedly!\")\n\nif __name__ == '__main__':\n  unittest.main()\n```\n\n## 延伸阅读\n\n* [GitHub Copilot 对话助手的提示设计](/zh/copilot/concepts/prompting/prompt-engineering)\n* [使用 GitHub Copilot 的最佳做法](/zh/copilot/get-started/best-practices)"}