Mockito thenReturn 返回不同的值

Mockito thenReturn returning different values

所以我有这样的测试:

public class TimesheetServiceTest {
    @Mock
    Repository repository;
    @Mock
    ServiceToMockResult serviceToMockResult;
    @InjectMocks
    private ServiceToTest serviceToTest = new ServiceToTestImpl();

    @Test
    public void testLongResult() {
        when(serviceToMockResult.getResult(any(String.class)))
                .thenReturn(20L); //it's supposed to always return 20L
        //8 items length result list
        List<Long> results = this.serviceToTest.getResults();
       //some more testing after ....
    }
}

如您所见,serviceToMock.getResult() 方法在 ServiceToTest 内部被调用。所以在这样做之后我得到了我期望的 8 个结果,但其中一些是值 0,而且我还注意到它总是在列表中的位置 5 和 7。值得注意的是,当我在测试中直接调用 serviceToMock.getResult() 而没有通过另一个 class 时,我得到了预期的结果。

预期结果

20, 20, 20, 20, 20, 20, 20, 20

实际结果

20, 20, 20, 20, 20, 0, 20, 0

虽然将模拟注入 bean/service 而不是创建它,但让它通过模拟创建。在处理之前还要初始化 Mockito anntotation。

示例:

public class TimesheetServiceTest {
    @Mock
    Repository repository;
    @Mock
    ServiceToMockResult serviceToMockResult;

    // let mockito create the service. 
    @InjectMocks
    private ServiceToTest serviceToTest;

    @Test
    public void testLongResult() {
        // Init mocks
        MockitoAnnotations.initMocks(this);

        when(serviceToMockResult.getResult(any(String.class)))
                .thenReturn(20L);
        // This should work fine.

    }
}

参数匹配器 any(String.class) 匹配任何字符串,不包括空值。

请参阅 ArgumentMatchers.any 文档:

public static <T> T any(Class<T> type)

Matches any object of given type, excluding nulls.

很可能您在调用 serviceToMockResult.getResult() 时使用了空参数。 由于此类调用未被存根,因此 return 类型的默认值为 returned(对于 long0