Reputation: 393
I'm new to unit testing and i had a simple question regarding the usage of verify
method used in Mockito. here's the class i used for testing.
public class Foo{
int n = 0;
void addFoo(String a){
if(a == "a")
add(1);
}
protected void add(int num){
n =1;
}
public int get(){
return n;
}
}
And here's my Unit test.
public class FooTest {
@Mock Foo f;
@Test
public void test() {
MockitoAnnotations.initMocks(this);
f.addFoo("a");
//Passes
Mockito.verify(f).addFoo("a");
//Fails
Mockito.verify(f).add(1);
}
}
And i get a
Wanted but not invoked:
f.add(1);
-> at FooTest.test(FooTest.java:22)
However, there were other interactions with this mock:
-> at FooTest.test(FooTest.java:16)
exception.
How do you verify that add(int num)
is called ?
Upvotes: 1
Views: 643
Reputation: 311143
I think you misunderstood the point of verify
.
In your test, Foo f
is a mock object - Foo
's internal implementation is ignored, and only the behavior you recorded on it (using when(f.someMethod().thenXXX
) would happen.
The point of mocking and verifying is to test interactions while ignoring the internal implementation.
In this example, you would probably have another class that uses Foo
, and you'd want to test whether it invokes the correct methods of the given Foo
instance.
Quick example:
Assume you have a class the uses the Foo
class you presented in your question:
public class FooUser {
private Foo f;
public void setFoo(Foo f) {
this.f = f;
}
public Foo getFoo() {
return f;
}
public void addToFoo(String string) {
f.add(string);
}
}
Now, you'd want to test that FooUser#addToFoo(String)
indeed invokes the correct add(String)
method of Foo
:
@RunWith (MockitoJUnitRunner.class)
public class FooUserTest {
@Mock Foo f;
FooUser fUser;
@Before
public void init() {
fUser = new FooUser();
fUser.setFoo(f);
}
@Test
public void test() {
fUser.addToFoo("a");
Mockito.verify(f).addFoo("a");
}
Upvotes: 3