如果测试类中存在多个测试方法,则Android JUnit测试方法会挂起

时间:2014-07-25 12:13:20

标签: android unit-testing junit

我正在为一个应用程序编写Android JUnit测试。我扩展ActivityInstrumentationTestCase2并在我的测试类中有多个测试方法。我不使用Robotium - 只是一个简单的Android JUnit测试。 当我一次运行测试方法时,第一个通过,下一个挂起。如果我单独运行它们,全部通过。在我的测试中发生的是,在每个测试方法中,我使用Activity_Under_Test启动getActivity(),然后执行某些操作,这将启动另一个活动,并且测试中的一个将自动销毁。我也尝试销毁新启动的活动(它被监视器捕获),但它在我的设备上保持打开状态,下一个测试方法挂起getActivity()。您能告诉我如何让下一个测试方法正确启动Activity_Under_Test吗?我不能给出实际代码,但这里有一些我正在做的样本:

public class Test extends ActivityInstrumentationTestCase2< Activity_Under_Test> {

    ... // local vars

    public Test() {
        super(Activity_Under_Test.class);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();

        instrumentation = getInstrumentation();
        context = instrumentation.getTargetContext();
        prefs = context.getSharedPreferences(...);
    }

    @Override
    protected void tearDown() throws Exception {
        if (activity != null) {
            activity.finish();
        }

        super.tearDown();
    }

    public void test1() {
        ... // change shared preferences so that Activity_ABC is started automatically from Activity_Under_Test

        monitor1 = instrumentation.addMonitor(Activity_ABC.class.getName(), null, false);

        activity = getActivity();

        // Activity_Under_Test starts automatically Activity_ABC and destroys itself
        activityABC = (Activity_ABC) mInstrumentation.waitForMonitorWithTimeout(monitor1, 5);
        assertNotNull(activityABC);

        instrumentation.runOnMainSync(new Runnable() {

            @Override
            public void run() {
                instrumentation.callActivityOnDestroy(activityABC);
            }
        });

        assertTrue(activityABC.isDestroyed());
        instrumentation.removeMonitor(monitor1);
    }

    public void test2() {
        ... // change shared preferences so that Activity_DEF is started automatically from Activity_Under_Test

        monitor2 = instrumentation.addMonitor(Activity_DEF.class.getName(), null, false);

        activity = getActivity();

        // Activity_Under_Test starts automatically Activity_DEF and destroys itself
        activityDEF = (Activity_DEF) mInstrumentation.waitForMonitorWithTimeout(monitor2, 5);
        assertNotNull(activityDEF);

        instrumentation.runOnMainSync(new Runnable() {

            @Override
            public void run() {
                instrumentation.callActivityOnDestroy(activityDEF);
            }
        });

        assertTrue(activityDEF.isDestroyed());
        instrumentation.removeMonitor(monitor2);
    }
}

如果您需要更多信息,请告诉我我会说些什么。

提前谢谢!

0 个答案:

没有答案