Issue
I have a class implements Runnable like this
public Processor implements Runnable{
public void run() {
while (true) {
//some code
sendRequest(object);
}
}
}
public void sendRequest(Object, object){
// do something to send the event
}
}
And in other pre-load class. I use
Processor processor = new Processor();
ExecutorService executor = Executors.newCachedThreadPool();
executor.execute(processor)
So my question is how can I unit test sendRequest method is called or not?
Solution
Separate the concerns : the Runnable
and the logic associated.
It will make in addition your code mode testable.
You could extract sendRequest()
in a Foo
class that the Processor
class depends on.
Then you have just to mock this Foo
class in your test and verify that the sendRequest()
method was invoked.
For example :
public Processor implements Runnable{
private Foo foo;
public Processor(Foo foo){
this.foo = foo;
}
public void run() {
while (true) {
//some code
foo.sendRequest(object);
}
}
}
And the test :
@Mock
Foo fooMock;
@Test
public void run() {
Processor processor = new Processor(fooMock);
ExecutorService executor = Executors.newCachedThreadPool();
executor.execute(processor);
executor.awaitTermination(someTime, TimeUnit.SECONDS);
Mockito.verify(fooMock).sendRequest(...);
}
Answered By - davidxxx