我正在尝试测试模块中的活动。 我只是试图在测试方法中启动此活动,但我总是有一个AssertionFailedError
。 我在网上搜索了这个问题,但找不到任何解决方案。 任何帮助表示赞赏。
这是我的测试类:
public class ContactActivityTest extends ActivityUnitTestCase { public ContactActivityTest() { super(ContactActivity.class); } @Override public void setUp() throws Exception { super.setUp(); } public void testWebViewHasNotSetBuiltInZoomControls() throws Exception { Intent intent = new Intent(getInstrumentation().getTargetContext(), ContactActivity.class); startActivity(intent, null, null); } @Override public void tearDown() throws Exception { super.tearDown(); } }
这是错误:
junit.framework.AssertionFailedError at android.test.ActivityUnitTestCase.startActivity(ActivityUnitTestCase.java:147) at com.modilisim.android.contact.ContactActivityTest.testWebViewHasNotSetBuiltInZoomControls(ContactActivityTest.java:29) at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:214) at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:199) at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191) at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176) at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:555) at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1763)
问候。
ActivityUnitTestCase的startActivity()方法只需要在主线程上调用。
这可以通过以下方式完成:
在测试方法之前使用@UiThreadTest注释:
@UiThreadTest public void testWebViewHasNotSetBuiltInZoomControls() throws Exception { Intent intent = new Intent(getInstrumentation().getTargetContext(), ContactActivity.class); startActivity(intent, null, null); }
使用Instrumentation类的runOnMainSync方法:
public void testWebViewHasNotSetBuiltInZoomControls() throws Exception { final Intent intent = new Intent(getInstrumentation().getTargetContext(), ContactActivity.class); getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { startActivity(intent, null, null); } }); }
我为什么是对的?