Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Mockito to verify a method is called in another method?

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.

like image 340
HenlenLee Avatar asked Nov 18 '25 02:11

HenlenLee


1 Answers

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());
like image 133
Yoav Gur Avatar answered Nov 20 '25 15:11

Yoav Gur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!