Mockito verify number of invocations in spring boot test

Viewed 2357

I'm trying to verify that a mocked method (fileSenderService.sendFile) was called exactly 2 times. For whatever reason Mockito never fails the test, no matter what number of invocations are expected. I'm using it like this:

verify(mockService, times(expectedNumberOfInvocations)).sendFile(any(String.class), any(byte[].class));

No matter what value I use in the times() method, the test always passes.

The MyService looks like this:

@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
    }

The test class

@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?
    }
}

The FileSenderService and its mock:

@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 Answers

If you are using @SpringBootTest for integration test cases you don't need to define any test config classes for mocks, you can simply use @MockBean annotation to inject mock into test context

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyServiceTest{

    @Autowired
    private MyService myService;

    @MockBean
    FileSenderService fileSenderService;

    @Test
    public void shouldCreateAndSendFiles(){
    myService.createAndSendFiles(); 
    verify(fileSenderService, times(2)).sendFile(any(String.class), any(byte[].class));
   }
}
Related