{"meta":{"title":"生成单元测试","intro":"副驾驶聊天 可帮助生成函数的单元测试。","product":"GitHub Copilot","breadcrumbs":[{"href":"/zh/copilot","title":"GitHub Copilot"},{"href":"/zh/copilot/tutorials","title":"教程"},{"href":"/zh/copilot/tutorials/copilot-chat-cookbook","title":"GitHub Copilot Chat 指南"},{"href":"/zh/copilot/tutorials/copilot-chat-cookbook/testing-code","title":"测试代码"},{"href":"/zh/copilot/tutorials/copilot-chat-cookbook/testing-code/generate-unit-tests","title":"生成单元测试"}],"documentType":"article"},"body":"# 生成单元测试\n\n副驾驶聊天 可帮助生成函数的单元测试。\n\n良好的单元测试套件对于任何project的成功至关重要。 但是，编写这些测试可能非常耗时，并且经常被忽视。 副驾驶聊天 可帮助为你生成这些测试。\n\n## 示例方案\n\n假设你有一个 Python 函数，用于在更新数据库之前验证数据。 你需要创建单元测试，以确保验证按预期方式执行。 你可以让 副驾驶聊天 为你生成这些测试。\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] 以下响应是示例。 副驾驶聊天 的回答是不确定的，因此你可能会得到与这里所显示的不同的回答。\n\n如果这是你第一次请求 副驾驶聊天 生成单元测试，它可能会询问你是否希望为项目配置单元测试。 在本示例中，我们假设你拒绝了此提议。\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/using-github-copilot/prompt-engineering-for-github-copilot)\n* [使用 GitHub Copilot 的最佳做法](/zh/copilot/using-github-copilot/best-practices-for-using-github-copilot)"}