为什么即使结果不是 3,测试也会通过任何数字?

Why the test past with any numbers even if the result isn't 3?

我从 Mockito 开始,在教程中有这个测试:

@Test
public void calculate_shouldUseCalculator_forAnyAddition() {
    // GIVEN
    final Random r = new Random();
    when(calculator.add(any(Integer.class), any(Integer.class))).thenReturn(3);

    // WHEN
    final int result = classUnderTest.calculate(
            new CalculationModel(CalculationType.ADDITION, r.nextInt(), r.nextInt())).getSolution();

    // THEN
    verify(calculator, times(1)).add(any(Integer.class), any(Integer.class));
    verify(calculator, never()).sub(any(Integer.class), any(Integer.class));
    assertThat(result).isEqualTo(3);
}

我不明白为什么测试通过了。两个任意整数相加的结果并不总是 3.

单元测试的目标是确保随后为计算类型参数等于 CalculationType.ADDITION.

的任何 CalculationModel 调用方法 add

你并不关心calculator.add()方法本身是否正常工作。您唯一应该检查它是否被 calculate 方法调用。因此,您可以使用任何参数的常量模拟其结果:

when(calculator.add(any(Integer.class), any(Integer.class))).thenReturn(3);

现在您断言,无论何时使用 CalculationType.ADDITION 调用 calculate,结果都等于您定义的常量。


考虑这个三段论:

如果:

一个。 calculate 调用 add

乙。 add returns 3

然后:

C. calculate returns 3