I have an Android
app that I'm working on and trying to write unit tests for it. The app is written with the MVP architecture and I am trying to test the Presenter-class.
Simplified method I'm trying to test looks like this:
public void userPressedButton() {
service.loadData(new Callback<Data>{
@Override
onResponse(Data data) {
view.showData(data);
}
});
}
Now I want to verify that when the userPressedButton
method is called view.showData(data)
is called.
I have tried several approaches but I can't seem to figure out how to test this.
Any ideas?
Edit: to clarify, I want to write a unit test
Interesting case.
What i would do is to:
1) - Create a concrete class for that particular Callback:
public class MyCallback implements Callback<Data>{
private View view;
public MyCallback(View view){
this.view = view;
}
@Override
onResponse(Data data) {
view.showData(data);
}
}
Now for this class you can write a unit test which would check whether the onResponse
method calls the showData
method of the view
field.
2) Having extacted the implementation to a concrete class, from the perspective of the class which contains the userPressedButton
method, it really is not essential what happens inside of the Callback class.
It is important that a concrete implementation of that interface has been passed:
public void userPressedButton() {
service.loadData(new MyCallback(view));
}
and finally the test:
@InjectMocks
MyClass myClass;
@Mock
Service service;
@Captor
ArgumentCaptor argCaptor;
@Before
public void init(){
MockitoAnnotations.initMocks(this);
}
@Test
public void shouldUseMyCallback(){
// Arrange
// set up myClass for test
// Act
myClass.userPressedButton();
Mockito.verify(service).loadData(argCaptor.capture());
// Assert
assertTrue(argCaptor.getValue instance of MyCallback);
}
So we check whether the loadData
method has been called with proper implementation.
Thats how i would test your case.
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