使用Robolectric测试Android Activity,复制Otto提供商

时间:2014-01-05 03:08:43

标签: android robolectric otto

我有一个小问题,想弄清楚如何使用Robolectric 2.2来测试我的Activity。我可能没有正确设置生命周期或整个测试...

在我的活动中,我有一个像这样的奥托制作人:

@Produce public GetAlarmList produceAlarmList() {
    Log.v(this, "Producing GetAlarmList event.");
    return new GetAlarmList(mAlarmList);
}

以下是我的测试。

@RunWith(RobolectricTestRunner.class)
public class GLarmListFragmentTests {

    //GLarmMain mActivity;
    ActivityController<GLarmMain> mController;

    @Before
    public void setUp() throws Exception {
        mController = Robolectric.buildActivity(GLarmMain.class);
    }

    @After
    public void tearDown() throws Exception {
        mController = mController.destroy();
    }

    @Test
    public void shouldHaveListFragment() {
        GLarmMain activity = mController.create().start().resume().visible().get();
        GLarmListFragment listFragment = (GLarmListFragment) activity.getSupportFragmentManager().findFragmentById(R.id.main_list_frag);
        assertNotNull(listFragment);
    }

    @Test
    public void shouldHaveListAdapter() {
        GLarmMain activity = mController.create().start().resume().visible().get();
        GLarmListFragment listFragment = (GLarmListFragment) activity.getSupportFragmentManager().findFragmentById(R.id.main_list_frag);
        FuncAlarmListAdapter listAdapter = (FuncAlarmListAdapter)listFragment.getListAdapter(); 
        assertNotNull(listAdapter);
    }
}

每次发布​​时,我都会收到:

java.lang.IllegalArgumentException: Producer method for type class ar.android.app.glarm.events.GetAlarmList found on type class ar.android.app.glarm.ui.GLarmMain, but already registered by type class ar.android.app.glarm.ui.GLarmMain.
    at com.squareup.otto.Bus.register(Bus.java:198)
    at ar.android.app.glarm.ui.GLarmMain.onResume(GLarmMain.java:461)
    at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1184)
    at android.app.Activity.performResume(Activity.java:5082)
    at org.fest.reflect.method.Invoker.invoke(Invoker.java:112)
    at org.robolectric.util.ActivityController$6.run(ActivityController.java:216)
    at org.robolectric.shadows.ShadowLooper.runPaused(ShadowLooper.java:256)
    at org.robolectric.util.ActivityController.invokeWhilePaused(ActivityController.java:214)
    at org.robolectric.util.ActivityController.resume(ActivityController.java:152)
    at ar.android.app.glarm.test.GLarmListFragmentTests.shouldHaveListAdapter(GLarmListFragmentTests.java:51)

有人有同样的问题吗?我该如何解决?

1 个答案:

答案 0 :(得分:0)

发现问题,留待此处参考。 我没有处理pause()/ onPause()生命周期步骤,因此从不调用:

@Override
protected void onPause() {
    super.onPause();
    Log.v(this, ".onPause()");
    mBus.unregister(this); // unregisters.
}

更改上面的代码解决了:

@After
public void tearDown() throws Exception {
    mController = mController.pause().stop().destroy();
}