Unit tests assert vs Mockito.verify()

Johan Fredin :

Fiddling around with Mockito for implementing unit tests of my services but for some reason I can't get this through my thick skull. My tests are passing but I am not conviced that I am doing it right.

Here is an example where I test the count() method. The method simply forwards the call to its repository and I wan't to verify that only that and nothing else happens. This is what I've got:

@RunWith(MockitoJUnitRunner.class)
public class PersonServiceImplTest {

    @Mock
    private PersonRepository personRepository;

    @InjectMocks
    private PersonServiceImpl personService;

    @Test
    public void testCount() {

        when(personRepository.count()).thenReturn(2L);

        long count = personService.count();

        assertEquals(2L, count);

        verify(personRepository).count();
    }
}

My test is passing but I have some questions.

  1. Is the assertEquals needed? as I understand it, whatever I put as the expected result of the method stub (.thenReturn(value..)) will ALWAYS be the value returned. Or could it be something else in this scenario?

  2. Do I need the verify? I feel like I do because I want to verify that personRepository.count() was actually called. Or is that redundant when I have assertEquals() as well?

  3. Do I need both assertEquals and verify?

  4. And finally, am I doing this right :)

Thank you

starf :

Yes, you are doing it right.

You are injecting a mock repository into a real service, then testing the service. When it comes to business logic in your service, anything could be happening. That's why it's important to verify the code with known inputs and known outputs, just like you're doing.

  1. You're checking the result of the business logic, given the response from the repository. This particular code is fairly straightforward, but imagine if the business logic was providing an average or a sum, not just the same value provided from the repository.

  2. and 3. The verify and the assertEquals are testing different things. The verify checks that your repository method was called, the assert checks that the service responded with the correct value. Imagine that your service method had a hard-coded return 2L. The assertEquals would pass, but the verify would fail.

  3. Yes, you're doing it right. What you're testing is linked to Why you're testing. Whether a particular assertion or verify is required is usually down to the individual situation. In this case, there is little point in testing that your repository method returns 2L, but there is a good case for testing that your service returns 2L. Similarly, there is no point in testing that the service method has been called, but there's a good case for testing that the repository method has been called.

You now have the tools to test your service, the next step is determining which tests to write.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=128544&siteId=1