所以我有这样的测试:
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()而没有通过其他类时,我得到了预期的结果。
预期结果
20,20,20,20,20
实际结果
20,20,20,20,20
发布于 2020-11-27 13:46:10
参数匹配器any(String.class)
匹配任何字符串,不包括空字符串。
请参阅ArgumentMatchers.any文档:
public static <T> T any(Class<T> type)
匹配任何给定类型的对象,不包括空。
很可能是使用空参数调用serviceToMockResult.getResult()。由于这样的调用没有存根,返回类型的默认值将被返回( 0
表示long
)。
发布于 2020-11-27 06:02:37
当将模拟注入到bean/服务而不是创建它时,让它通过模拟创建。在加工前也要进行Mockito的环化。
示例:
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.
}
}
https://stackoverflow.com/questions/65037723
复制