Robolectric: actionBar.hide() returns Null

2019-08-02 02:48发布

问题:

I'm new to Android unit testing and I'm using Robolectric as a testing framework. I use Robolectric 2.2.

I'm trying to test an activity which is like that :

public class LoginActivity extends SherlockActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_login);

ActionBar abs = getSupportActionBar();
abs.hide();
}

and here's my test class :

@RunWith(RobolectricTestRunner.class)
public class LoginActivityTest {

@Before 
public void setUp() throws Exception
{
    System.setProperty("dexmaker.dexcache", "/sdcard");
    activity = Robolectric.buildActivity(LoginActivity.class).create().get();
}

@Test
public void should_loginActivity_created() throws Exception {

    assertNotNull(activity);

}

I'm getting this error :

java.lang.NullPointerException  
at auth.LoginActivity.onCreate(LoginActivity.java:119)

This line refers to abs.hide();

NOTE : I tried Xian's Gist and it did not work.

Also I try to create ShadowSherlockActivity like this But I have no idea how to use this shadow class to create activity like :

activity = Robolectric.buildActivity(LoginActivity.class).create().get();

NOTE 2 : I try to use Robolectric Snapshot 2.3 but it did not solved.

Thanks.

回答1:

As @ersentekin and I worked out in the comments, here is a Gist that takes @Xian's Gist with a suggestion from marsucsb and modifies it to work with Robolectric 2.2+



回答2:

Have u added the android:theme in your androidmanifest.xml

<application android:icon="@drawable/icon" android:label="@string/app_name"
    android:debuggable="false" android:theme="@style/Theme.Sherlock">