2

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.

1

1 Answer 1

8

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()); 
Sign up to request clarification or add additional context in comments.

3 Comments

So how to test classb.sendRequest(this) is called when classa.publish() is called without taking Class B as a parameter?
You can't. You have to refactor. You could also add a ClassB member field, and use a setter to set the mock. But some refactoring is mandatory.
@HenlenLee OT: Since the only thing that call As publish method does is calling a method on its parameter passing itself along the question arises: Why does it need to be in class A? could't the caller of a.publish(b); call b.sendRequest(a); directly? That would remove the dependency of class A to class B completely...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.