简体   繁体   中英

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() .

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 .

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;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM