# 更新单元测试以匹配代码更改

副驾驶聊天 可帮助更新测试。

对代码进行更改时，更新任何测试以验证新行为并捕获新代码引入的任何 bug 非常重要。 副驾驶聊天 可以帮助你快速更新测试，使其与代码变化保持一致，从而确保你的测试套件始终与实现保持同步。

## 示例方案

假设你有一个 Python 函数， `calculate_discount`用于确定给定购买金额的折扣。 在原始代码中，对于超过 100 美元的金额，可享受 10% 的折扣。 你正在更改函数的逻辑，以便只有价格超过 150 美元的项目获得 10% 折扣，而价格超过 200 美元的项目现在享有 20% 折扣。

### 原始代码

在原始代码中，购买价格超过 100 美元可获得 10% 折扣。

```python
def calculate_discount(amount: float) -> float:
    if amount > 100:
        return amount * 0.1  # 10% discount
    return 0.0
```

### 更新的代码

在更改的代码中，只有超过 150 美元的金额将获得 10% 折扣，超过 200 美元的金额现在将获得 20% 折扣。

```python id=calculate_discount
def calculate_discount(amount: float) -> float:
    if amount > 200:
        return amount * 0.2  
    elif amount > 150:
        return amount * 0.1
    return 0.0
```

### 现有测试

此示例演示为原始代码编写的现有测试。

```python
import unittest
from discount import calculate_discount

class TestCalculateDiscount(unittest.TestCase):
    def test_discount_above_100(self):
        # $140 should get a $14 discount (10%)
        self.assertAlmostEqual(calculate_discount(140), 14.0)
    
    def test_discount_below_100(self):
        # $80 should get no discount
        self.assertEqual(calculate_discount(80), 0.0)

    def test_discount_exactly_100(self):
        # $100 is not above 100, so no discount
        self.assertEqual(calculate_discount(100), 0.0)

if __name__ == '__main__':
    unittest.main()
```

## 示例提示

可以请求 副驾驶聊天 识别并更新受逻辑更改影响的任何测试。

```copilot
Given the update to the `calculate_discount` function, update the unit tests that may fail or become outdated as a result.
```

## 示例响应

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

副驾驶聊天 分析你的代码和现有测试，并确定哪些测试会失败，哪些测试在你的代码更改后会产生误导。

例如，副驾驶聊天 说明了：

* `test_discount_above_100` 现在将**失败**
* `test_discount_below_100` 和 `test_discount_exactly_100` 将通过，但它们现在**具有误导性**，因为 10% 折扣的门槛现在是 150 美元，而不是 100 美元。

此外，副驾驶聊天 标识任何**缺失的测试覆盖范围**，例如金额超过 200 美元的新 20% 折扣等级。

副驾驶聊天 提出了更新的测试集。

### 更新的测试

```python
import unittest
from discount import calculate_discount

class TestCalculateDiscount(unittest.TestCase):
    def test_discount_above_200(self):
        # $250 should get a $50 discount (20%)
        self.assertAlmostEqual(calculate_discount(250), 50.0)

    def test_discount_above_150(self):
        # $175 should get a $17.50 discount (10%)
        self.assertAlmostEqual(calculate_discount(175), 17.5)

    def test_discount_at_or_below_150(self):
        # $150 is not above 150, so no discount
        self.assertEqual(calculate_discount(150), 0.0)
        # $80 should get no discount
        self.assertEqual(calculate_discount(80), 0.0)

if __name__ == '__main__':
    unittest.main()
```

## 延伸阅读

* [GitHub Copilot 对话助手的提示设计](/zh/enterprise-cloud@latest/copilot/using-github-copilot/prompt-engineering-for-github-copilot)
* [使用 GitHub Copilot 的最佳做法](/zh/enterprise-cloud@latest/copilot/using-github-copilot/best-practices-for-using-github-copilot)