Reputation: 2445
I have a code as belows :
public class D {
public static void main(String[] args) {
C c = Mockito.mock(C.class);
G g = Mockito.mock(G.class);
doReturn(g).when(c).getResult(eq(new A(new B())), eq(new F()));
verify(c, times(1)).getResult(eq(new A(new B())), eq(new F()));
}
}
When I try to run the code , I get this message :
Exception in thread "main" Wanted but not invoked:
c.getResult(
info.sanaulla.A@46f5f779,
info.sanaulla.F@1c2c22f3
);
-> at info.sanaulla.D.main(D.java:15)
Actually, there were zero interactions with this mock.
at info.sanaulla.D.main(D.java:15)
I referred this link but couldn't understand how to modify the above code to make it workable : Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock
Can someone please help.
The above error got resolved by adding c.getResult(new A(new B()), new F()); above
Exception in thread "main" Argument(s) are different! Wanted:
c.getResult(
info.sanaulla.A@12bc6874,
info.sanaulla.F@4c75cab9
);
-> at info.sanaulla.D.main(D.java:17)
Actual invocation has different arguments:
c.getResult(
info.sanaulla.A@de0a01f,
info.sanaulla.F@1ef7fe8e
);
-> at info.sanaulla.D.main(D.java:16)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at info.sanaulla.D.main(D.java:17)
What am I Missing? Classes I have been using :
public final class A {
B b;
public A(B b) {
this.b = b;
}
}
public class B {
}
public class C {
public C() {
}
public G getResult(A a, F f) {
G g = new G();
return g;
}
}
public class F {
}
Upvotes: 0
Views: 737
Reputation: 69439
You never call a function of mock c.
verify
checks if the mock c is called one time in your test case.
UPDATE:
change you code to:
public class D {
public static void main(String[] args) {
C c = Mockito.mock(C.class);
G g = Mockito.mock(G.class);
B b = new B();
A a = new A();
F f = new F();
doReturn(g).when(c).getResult(eq(a), eq(f));
c.getResult(a, f);
verify(c, times(1)).getResult(eq(a), eq(f));
}
}
Because in your code you ever create a new Instance of an object, wich are different after every initilization.
Upvotes: 3
Reputation: 2564
Try the following:
public class D {
public static void main(String[] args) {
// mock a dummy so that we do not have to call A's actual methods
A a = Mockito.mock(A.class);
when(a.foo()).thenReturn("bar");
// run the actual method of C
new C().getResult(a, new F());
// verifies that this method was called
verify(c, times(1)).getResult(any(A.class), any(F.class));
}
}
You should never mock
the class that you want to test, as that will create a dummy object. All the when
methods are for telling your dummy classes what to return when their methods are called.
Upvotes: 0