Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么即使结果不是',测试也会以任何数字通过;t3?_Java_Mockito_Junit5 - Fatal编程技术网

Java 为什么即使结果不是',测试也会以任何数字通过;t3?

Java 为什么即使结果不是',测试也会以任何数字通过;t3?,java,mockito,junit5,Java,Mockito,Junit5,我从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 resul

我从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
调用
calculation
,结果都等于您定义的常量


考虑一下这个三段论:

如果

A.
计算
调用
添加

B.
add
返回3

然后


C.
calculate
返回3

您已经将
add()
方法存根为返回3,无论您传递给它的是什么整数。这就是
when().thenReturn()
所做的,但是如果在“给定”部分中添加任何两个整数,您实际上是在告诉它返回
3
。因此,无论函数的参数是什么,thenReturn都会将结果设为3。谢谢@米奇:是的,这是嘲弄的主要特征。你告诉一些方法返回你想要的结果。然后确保其他方法(您测试的方法)正常工作,假设模拟的方法工作正常。感谢更新^^,是的,因此无论函数返回什么结果,模拟测试仅在函数被调用,而不是结果正确时才允许参数。调用“classUnderTest.calculate(新的CalculationModel(CalculationType.ADDITION,r.nextInt(),r.nextInt())).getSolution();”始终返回3,因为返回参数时,即使实函数返回另一个值,@Mitch Yes,
calculator.add(…)
也会返回您告诉它返回的任何值。在这个特定的单元测试中,它是3,但也可以是其他值,这取决于您的需要。