我在验证一个被模仿的方法( fileSenderService.sendFile
)正好打了两次电话。无论出于何种原因,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?
}
}
filesenderservice及其模拟:
@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;
}
1条答案
按热度按时间nimxete21#
如果您正在使用
@SpringBootTest
对于集成测试用例,您不需要为mock定义任何测试配置类,您可以简单地使用@mockbean注解将mock注入到测试上下文中