I have a method that receives a listener (interface) with onSuccess(result) and onFail(error) methods.
The tested method performs some actions (on another thread) and eventually calls the listener with an answer.
Example code for the method itself (not the test):
testedObject.performAsyncAction("some data", new IListener(){
@Override
public void onSuccess(int result) {
if (result == 1) { /* do something */ }
else if (result == 2) { /* do something else */ }
}
@Override
public void onFailure(Error error) {
if (error.getMessage().equals("some error")) { /* do something */ }
else if (error.getMessage().equals("another error")) { /* do something else */ }
}
});
I want to have few tests on this method:
Thank you!
For this case I use the Mockito Answer object. This would be a test for a success case:
Answer<Void> myAnswer = new Answer<Void>() {
public Void answer(InvocationOnMock invocation) {
Callback callback = (Callback) invocation.getArguments()[1]; // second argument in performAsyncAction
callback.onSuccess(1); // this would be 1 or 2 in your case
return null;
}
};
doAnswer(myAnswer).when(testedObject).performAsyncAction("some data", any(Callback.class));
For the failure case, just create another test with a different answer. For more info, check this blog post.
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