stack
stack

Reputation: 265

Mocking getActionBar() returns null

I'm testing an activity, and I want to mock getActionBar(). I've tried doing it the usual way, that is

ActionBar mActionBar;

@Before
public void setup() {
    initMocks(this);
    mActionBar = Mockito.mock(ActionBar.class);   
}

@Test 
public void someTest(){
    when(activity.getActionBar()).thenReturn(mActionBar);
}

But that doesn't seem to do anything, because I still get an NPE, when I try using the action bar in the activity after getActionBar().

Upvotes: 0

Views: 250

Answers (2)

Eugen Martynov
Eugen Martynov

Reputation: 20130

I assume you're setting Activity as it is written in Robolectric tutorial. There is no simple way to mock real activity method inside of activity code itself.

I would suggest you create TestMyActivity that extends your activity and lives only in test sources. Then you can override getActionBar() (probably getSupportActionBar())).

public class TestMyActivity extends MyActivity {
   @Override
   ActionBar getActionBar() {
      return mockedActionBar;
   }
}

Upvotes: 0

john16384
john16384

Reputation: 8054

You are probably calling other methods on the mocked ActionBar in the code you are testing, like for example:

Tab tab = actionBar.getSelectedTab()

This returns null. Using tab then will result in a NPE.

This means you will need to mock more, for example:

when(actionBar.getSelectedTab()).thenReturn(mock(Tab.class));

Now the above example will return a mocked Tab.

Upvotes: 1

Related Questions