[wp_ad_camp_1]
Previously, I posted Void methods and Mockito in Java that verifies if any of the methods of a object passed as a argument were invoked.
This time we want to alter the behavior of a method that returns void.
Mock to alter a Method Behavior
Consider this code snippet:
[wp_ad_camp_2]
1 2 3 4 5 6 7 | public class Animal { private boolean isFriend; public void beFriend(Animal anotherAnimal) { anotherAnimal.isFriend = true; } } |
How are we to mock this using Mockito
? We want to test for a scenario where
1 | anotherAnimal.isFriend = false; |
Introducing Mockito.doAnswer
doAnswer
allows us to change something within a method particularly objects passed as arguments.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | @Test public void testUnfriendly() { Animal dog = Mockito.mock(Animal.class); Mockito.doAnswer(new Answer<Animal>() { @Override public Animal answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); Animal animal = (Animal) args[0]; // We changed the behavior animal.isFriend = false; return null; } }).when(dog).beFriend(Matchers.<Animal> any()); } |
When you inject the dog
object to some object, it will be dealing with an unfriendly animal.
[wp_ad_camp_3]