如果使用得当,AI在测试的枚举部分表现出色——它能够头脑风暴边界情况并快速编写模板代码。但您必须验证断言是否有意义,因为AI会乐意写出通过而不证明任何东西的测试。
// Function under test, with its contract:
// applyDiscount(price, percent) -> price reduced by percent.
// Contract: percent must be 0..100; throws RangeError otherwise. price >= 0.
function applyDiscount(price, percent) {
if (percent < 0 || percent > 100) throw new RangeError('percent out of range');
return price - (price * percent) / 100;
}
// AI-suggested test cases (Jest) — note the edge and error paths, not just happy path:
test('applies a normal discount', () => {
expect(applyDiscount(100, 20)).toBe(80); // happy path
});
test('0% leaves price unchanged', () => {
expect(applyDiscount(100, 0)).toBe(100); // boundary: lower edge
});
test('100% makes it free', () => {
expect(applyDiscount(100, 100)).toBe(0); // boundary: upper edge
});
test('rejects percent above 100', () => {
expect(() => applyDiscount(100, 150)).toThrow(RangeError); // error path
});
AI提出了边界情况(0和100)以及您可能遗漏的错误路径。您的任务是确认toBe(80)是正确的期望值,而不仅仅是函数碰巧返回的值。
测试的难点不在于键入test(...)块——而在于想到您本来会遗漏的情况,而AI在这种广泛的思考上确实很擅长。但除非您告诉它,否则它不知道您的代码应该做什么,所以如果不加监控,它倾向于写出镜像实现的测试(它们通过,但即使函数错误也会通过)。将AI视为边界情况生成器而由您掌控断言,可以给您广泛的覆盖范围和真正的正确性——AI提供速度,您提供判断。
一个包含详细解答的 IT 面试题库——从初级到高级。
捐赠