Reputation:
I have simple class with void method.
public class Simple {
public Void doSomething() {}
}
And I want to increment a number in my test after calling doSomething()
.
@Test
public void test1() {
int number = 0;
Simple simple = Mockito.mock(Simple.class);
Mockito.when(simple.doSomething()).then(number++);
}
Of course it is causing compilation error. How can I increment number
after calling doSomething()
?
Alternative solution:
It's very bad practice but it's alternative solution for best answer below.
private int number = 0;
@Test
public void test1() {
Simple simple = Mockito.mock(Simple.class);
Mockito.when(simple.doSomething()).thenReturn(increment());
}
private Void increment() {
number++;
return null;
}
Upvotes: 3
Views: 5739
Reputation: 137084
It is not clear from your question why you would want to have such a thing. The code in this answer is not good practice and I won't recommend it.
The first problem is that your method returns void
so you can't stub it with Mockito.when
. You need to use Mockito.doWhen
.
In this code, I use Mockito.doAnswer
to write a custom code inside the answer part:
@Test
public void test1() {
int[] number = { 0 };
Simple simple = Mockito.mock(Simple.class);
Mockito.doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
number[0]++;
return null;
}
}).when(simple).doSomething();
}
The trick is to store the number inside a final variable (in this case, an array) and increment its only value in the answer part. Each time doSomething()
will be called, it will be incremented and you will have the count inside number[0]
.
The same code can be made more compact with Java 8:
Mockito.doAnswer(invocation -> number[0]++).when(simple).doSomething();
Upvotes: 9