java-使用Robolectric时如何监视活动
作者:互联网
我是Android的新手,我正在与Robolectric一起进行单元测试.
我正面临以下问题.
我有一个要测试的活动.
MainActivity.java
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
private NavigationDrawerFragment mNavigationDrawerFragment;
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
@Override
public void onNavigationDrawerItemSelected (int position) {
...
}
}
这是测试类:
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class)
public class MainActivityTests {
private ActivityController<MainActivity> controller;
private MainActivity activity;
private MainActivity spy;
@Test
public void onCreate_shouldStartNavigationDrawerFragment () {
controller = Robolectric.buildActivity(MainActivity.class);
activity = controller.get();
assertThat(activity).isNotNull();
spy = spy(activity);
spy.onCreate(null);
verify(spy).onCreate(null);
}
}
但是我收到以下异常:
java.lang.IllegalStateException:在spy.onCreate(null)行的onCreate()之前,Activities无法使用系统服务.
我已经搜寻了几个小时,并且尝试了几种变通方法(盲目),但均未成功.可以请任何人指导我吗?
解决方法:
这就是我的诀窍.我先使用attach()进行活动监视.经过Robolectric 3.0测试
private MainActivity spyActivity;
@Before
public void setUp(){
MainActivity activity = Robolectric.buildActivity(MainActivity.class).attach().get();
spyActivity = spy(activity);
spyActivity.onCreate(null);
}
标签:unit-testing,android-testing,robolectric,java,android 来源: https://codeday.me/bug/20191120/2042623.html