Jeni
Jeni

Reputation: 1118

Mocking android method in Junit test

I am trying to create some JUnit tests for my Android app.

In the app I have the following method, which I am trying to get tested:

public void checkBoxAction(View v) {
    CheckBox cb = (CheckBox) v;
    Boolean isChecked = cb.isChecked();
    //Do stuff
}

I am using Mockito and I have got this far:

// ...
CheckBox dummyV = new CheckBox(mMockContext);
Mockito.when(dummyV.isChecked()).thenReturn(true);
item.checkBoxAction(dummyV);
// ...

But when I run the test I get error:

java.lang.RuntimeException: Method isChecked in
android.widget.CompoundButton not mocked...

I think the problem is that in the method checkBoxAction, the isChecked method is not executed on v, but on other object. Is this assumption correct? Is this the problem? And how can I fix it? Or there is something else?

Upvotes: 0

Views: 506

Answers (1)

Juan Cruz Soler
Juan Cruz Soler

Reputation: 8254

You should mock the CheckBox if you want to use Mockito.when, try:

CheckBox dummyV = mock(CheckBox.class);

Upvotes: 1

Related Questions