{"meta":{"title":"测试自动化","intro":"有关编写单元测试的特定于文件的说明。","product":"GitHub Copilot","breadcrumbs":[{"href":"/zh/copilot","title":"GitHub Copilot"},{"href":"/zh/copilot/tutorials","title":"教程"},{"href":"/zh/copilot/tutorials/customization-library","title":"定制化库"},{"href":"/zh/copilot/tutorials/customization-library/custom-instructions","title":"自定义说明"},{"href":"/zh/copilot/tutorials/customization-library/custom-instructions/testing-automation","title":"测试自动化"}],"documentType":"article"},"body":"# 测试自动化\n\n有关编写单元测试的特定于文件的说明。\n\n> \\[!NOTE]\n>\n> * 此库中的示例旨在提供灵感，建议进行相应调整，使其更特定于你的项目、语言和团队流程。\n> * 如需获取社区提供的有关特定语言和场景的自定义指令示例，请参阅[出色的 GitHub Copilot 自定义内容](https://github.com/github/awesome-copilot/blob/main/docs/README.instructions.md)仓库。\n> * 可以跨不同范围应用自定义指令，具体取决于要在其中创建自定义指令的平台或 IDE。 有关详细信息，请参阅“[关于自定义GitHub Copilot 响应](/zh/copilot/concepts/response-customization)”。\n\n此示例使用 `python-tests.instructions.md` 字段显示了特定于路径的 `applyTo` 文件，该文件仅适用于仓库中的 Python 测试文件。 有关特定于路径的说明文件的详细信息，请参阅 [为GitHub Copilot添加存储库自定义说明](/zh/copilot/how-tos/configure-custom-instructions/add-repository-instructions#using-one-or-more-instructionsmd-files)。\n\n````text copy\n---\napplyTo: \"tests/**/*.py\"\n---\n\nWhen writing Python tests:\n\n## Test Structure Essentials\n- Use pytest as the primary testing framework\n- Follow AAA pattern: Arrange, Act, Assert\n- Write descriptive test names that explain the behavior being tested\n- Keep tests focused on one specific behavior\n\n## Key Testing Practices\n- Use pytest fixtures for setup and teardown\n- Mock external dependencies (databases, APIs, file operations)\n- Use parameterized tests for testing multiple similar scenarios\n- Test edge cases and error conditions, not just happy paths\n\n## Example Test Pattern\n```python\nimport pytest\nfrom unittest.mock import Mock, patch\n\nclass TestUserService:\n    @pytest.fixture\n    def user_service(self):\n        return UserService()\n\n    @pytest.mark.parametrize(\"invalid_email\", [\"\", \"invalid\", \"@test.com\"])\n    def test_should_reject_invalid_emails(self, user_service, invalid_email):\n        with pytest.raises(ValueError, match=\"Invalid email\"):\n            user_service.create_user({\"email\": invalid_email})\n\n    @patch('src.user_service.email_validator')\n    def test_should_handle_validation_failure(self, mock_validator, user_service):\n        mock_validator.validate.side_effect = ConnectionError()\n\n        with pytest.raises(ConnectionError):\n            user_service.create_user({\"email\": \"test@example.com\"})\n```\n````"}