Reputation: 3121
I'm trying to test one class which makes a method call and wait from response throug a listener.
These are the interfaces inside the interactor. When I call fetch
, then one of the listener fuctions is called back.
interface Interactor {
void fetch(int offset, int size);
}
interface InteractorListener {
void onReady(List<Result> results);
void onError();
}
public class MyInteractor implements Interactor{
private ImageInteractorListener listener;
public MyInteractor() {}
public onAttach(ImageInteractorListener listener) {
this.listener = listener;
}
public void fetch(int offset, int size) {
// Make asyncrhonous task
// and manage the response in the next method
}
public void onAsyncroouTaskResponse() {
if (someChecks) {
listener.onReady(List<Result> results);
} else {
listener.onError();
}
}
}
public class MyClass implements ImageInteractorListener {
public MyClass() {
MyInteractor interactor = new Interactor();
interactor.onAttach(this);
interactor.fetch(1,1);
}
@Override
void onReady(List<Result> results) {
// doThings
}
@override
void onError() {
// doThings
}
}
This is how my classes are maked. I need to test MyClass
, so I need to mock Interactor callback
I have tried different sollutions with different problems, so right now I don't have a final code or error. But no one works..
Thank you.
Upvotes: 2
Views: 4279
Reputation: 27226
Dimitry's approach is good, I'd personally not call fetch, since your onAsyncroouTaskResponse()
is public, I'd call that and then verify(yourmock).onError()
or similar to make sure it was called.
Another approach I make sometimes, is create a "TestableSubject" that is just a class extends YourOriginalClass
where you override certain methods and keep a count of the number of times it was called, or similar. Sometimes, due to the nature of some classes, you can't mock them all (final, abstract stuff, private, etc.).
If what you want (and perhaps should) test is that upon completion of your asynchronous task, your call back is called (regardless of the outcome), then I'd skip the fetch part, you can test that fetch fires the job in another test, but I think here you are more interested in the later part.
Upvotes: 1
Reputation: 23952
Assuming that you're testing MyClass
you can just manually call your callback
// Test that errors are handled
// Given
Interactor interactor = mock(Interactor.class);
MyClass myClass = new MyClass(interactor);
// When
interactor.fetch(0, 0); // this call is optional, I just added it for clarity
myClass.onError();
// Then
// verify something
Upvotes: 1