I have a class A with a publish() method. In the method will call another method and pass the class A object as a parameter to Class B.
public class A {
public void publish() {
ClassB classb = new ClassB();
classb.sendRequest(this)
}
}
The question is how to use Mockito to verify the sendRequest method is called when the publish() method is called? I am new to Mockito.
You can't use Mockito if you create a new ClassB instance in your method.
You should refactor publish() to take ClassB as a parameter, and then you can send your Mockito mock instead of a real ClassB, and verify on it.
Like so:
public class A {
public void publish(ClassB classb){
classb.sendRequest(this)
}
}
And in your test:
ClassB mockClassB = mock(ClassB.class);
A a = new A();
a.publish(mockClassB);
verify(mockClassB, times(1)).sendRequest(any());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With