我想验证一个被模拟的方法 (fileSenderService.sendFile
) 被调用了恰好2次。但无论期望的调用次数是多少,Mockito 都没有引发测试失败。我是这样使用它的:
verify(mockService, times(expectedNumberOfInvocations)).sendFile(any(String.class), any(byte[].class));
无论在 times() 方法中使用什么值,测试总是通过。
MyService 的代码看起来像这样:
@Service
public class MyServiceImpl implements MyService {
@Autowired
private FileSenderService fileSenderService;
public void createAndSendFiles(){
//doSomeStuff, prepare fileNames and fileContents(byte arrays)
//execute the sendFile twice
fileSenderService.sendFile(aFileName, aByteArray); //void method; mocked for testing
fileSenderService.sendFile(bFileName, bByteArray); //void method; mocked for testing
}
测试类
@RunWith(SpringRunner.class)
@WebAppConfiguration
@SpringBootTest(classes = {Application.class, FileSenderServiceMock.class})
@ContextConfiguration
public class MyServiceTest{
@Autowired
private MyService myService;
@Autowired
FileSenderService mock;
@Test
public void shouldCreateAndSendFiles(){
myService.createAndSendFiles(); //inside this method sendFile() is called twice
verify(mock, times(999)).sendFile(any(String.class), any(byte[].class)); //THE PROBLEM - why times(999) does not fail the test?
}
}
文件发送服务及其模拟:
@Service
public class FileSenderServiceImpl implements FileSenderService {
@Override
public void sendFile(String name, byte [] content) {
//send the file
}
}
//used for testing instead of the actual FileSenderServiceImpl
public class FileSenderServiceMock {
@Bean
@Primary
public FileSenderService getFileSenderServiceMock(){
FileSenderServicemock = Mockito.mock(FileSenderService.class, Mockito.RETURNS_DEEP_STUBS);
doNothing().when(mock).sendFile(isA(String.class), isA(byte[].class));
return mock;
}