简体   繁体   中英

Initialize Activity For Unit Testing

I am unit testing an Activity .

private MyActivity _controller;

@Before
public void setUp() throws Exception
{
    ShadowLog.stream = System.out;

    _controller = Mockito.spy(new MyActivity());
}

However when I go to test it:

@Test
public void testInitRoot() throws Exception
{
    _controller.initRoot();
}

I get a crash:

java.lang.NullPointerException at android.view.ContextThemeWrapper.initializeTheme(ContextThemeWrapper.java:135)

After research I believe this is because the context is null and it can't properly get resources.

My question is: how do I actually create an Activity object for the sole purpose of testing? I run in Robolectric so I'm not looking to use Intent and startActivity . I'm looking for something like

MyActivity activity = new MyActivity(validContext);

Use Robolectric.setupActivity() to start your activity.

private MyActivity mActivity;
mActivity = Robolectric.setupActivity(MyActivity.class);

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