It’s been a while I didn’t post anything…
Today I’m back with Mockito 🙂
I played with it on my project and I learn some stuff… Ok, it’s mainly because I had some errors in my tests but still…
It’s always good to share even if I am the only one who use this samples!
I don’t want to present what is Mockito, use Google for that purpose!
I just want to share how I use it in my projects, I you may know, Mockito is very helpful when you need to test a particular component without using the whole application, it is useful for unit testing but even for integration tests when you do not have access to all external APIs for example.
The simplest way to use it is to replace the real implementation by the mock and then you can instruct him how he should behave in your test, here’s a simple example with a (Spring) repository who should return a bunch of data:
Mockito.when(birdRepository.getBirds(anyString(), anyBoolean(), anyBoolean(), anyBoolean())) .thenReturn(buildFakeBirds());
Here, we have a birdRepository (injected thanks to Spring) and we teach it to return a list of fake objects, this is probably the simplest way to do it.
But sometime, you receive an error telling that Mockito cannot call do what you asked for (WrongTypeOfReturnValue)… But what’s the hell?
In that case, you can refactor your test this way:
Mockito.doReturn(buildFakeBirds()) .when(birdRepository).getBirds(anyString(), anyBoolean(), anyBoolean(), anyBoolean());
Almost the same but for some obscure reason, it solves the error.
In the 2 examples above, the mock is always returning the same object, sometime, you want your mock to return different instances, or at least call the method each time (I had this issue when I was working on tests involving cache), in that particular case, you can write the test that way:
Mockito.when(birdRepository.getBirds(anyString(), anyBoolean(), anyBoolean(), anyBoolean())) .thenAnswer(new Answer() { @Override public Bird answer(final InvocationOnMock invocation) throws Throwable { return buildFakeBirds(); } });
In some cases, you may need to check how many times a method is called, then Mockito can also help on this:
Mockito.doReturn(buildFakeBirds()) .when(birdRepository).getBirds(anyString(), anyBoolean(), anyBoolean(), anyBoolean()); Collectionbirds = birdService.findBirds(); //normally, the method should have been called once verify(birdRepository, times(1)).getBirds(anyString(), anyBoolean(), anyBoolean(), anyBoolean());
Mockito is simply amazing 😀