Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: JUnit + Mockito, test callback?

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

like image 823
JesperQv Avatar asked Mar 02 '17 16:03

JesperQv


1 Answers

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.

like image 190
Maciej Kowalski Avatar answered Sep 23 '22 23:09

Maciej Kowalski