Java – mockito: how to run some code using the stub method when calling
I want to stub a repository class to test another class with a repository (holder class) The repository interface supports CRUD operations and has many methods, but my unit test of the holder class only needs to call two of them Repository interface:
public interface IRepo {
public void remove(String... sarr);
public void add(String... sarr);
//Lots of other methods I don't need Now
}
I want to create a repository simulation, which can store instances, define logic only for addition and deletion, and provide a method to check the contents stored in it after calling addition and deletion
If I do:
IRepo repoMock = mock(IRepo.class);
Then I have a stupid object that doesn't work in any way It doesn't matter. Now I just need to define the behavior of adding and deleting
I can create a set < string > and stub. There are only two methods to process the set Then I will instantiate a holder with irepo, inject a partial stub simulation, and after executing the holder, check the set to verify that it contains what it should be
I managed to use the deprecated method stubvoid and partially deleted a void method, such as remove:
Set<String> mySet = new HashSet<>();
stubVoid(repoMock).toAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
String[] stringsToDelete = (String[]) args[0];
mySet.removeAll(Arrays.asList(stringsToDelete));
return null;
}
}).on().remove(Matchers.<String>anyVararg());
But it's deprecated, and it's much better than creating a partial implementation for irepo Is there a better way?
Note: Java 7 only answers, which should run in Android
Solution
You can use
Mockito.doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
//DO SOMETHING
return null;
}
}).when(...).remove(Matchers.<String>anyVararg());
From Javadoc:
doAnswer(new Answer() {
public Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
Mock mock = invocation.getMock();
return null;
}}).when(mock).someMethod();
See the example in Javadoc for mockito
