Android - ActivityUnitTestCase 测试类中 startActivity 方法上的 AssertionFailedError

标签 android unit-testing assertion start-activity activityunittestcase

我正在尝试测试模块中的 Activity 。我只是想在测试方法中开始这个 Activity ,但我总是有一个 AssertionFailedError。我在网上搜索了这个问题,但找不到任何解决方案。任何帮助表示赞赏。

这是我的测试课:

public class ContactActivityTest extends ActivityUnitTestCase<ContactActivity> {

    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() 方法只需要在主线程上调用。

这可以通过以下方式完成:

  1. 在您的测试方法之前使用 @UiThreadTest 注释:

    @UiThreadTest
    public void testWebViewHasNotSetBuiltInZoomControls() throws Exception {
        Intent intent = new Intent(getInstrumentation().getTargetContext(),
                ContactActivity.class);
        startActivity(intent, null, null);
    }
    
  2. 使用 runOnMainSync Instrumentation 类的方法:

    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);
               }
            });
     }
    

Why am I right?

关于Android - ActivityUnitTestCase 测试类中 startActivity 方法上的 AssertionFailedError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24576932/

相关文章:

java - 如何在android studio中的whatsapp上自动发送消息

android - 谷歌地图代码中的 BadParcelableException

java - Spring3/Hibernate3/TestNG : some tests give LazyInitializationException, 有些没有

c++ - C++调试断言失败

java - 在android中的自定义日期时间选择器中显示本地格式

android - GradientDrawable绘制不同颜色的setColor方法

c# - 如何测试返回数据表的方法?

c# - 如何对 ASP.NET Web 窗体进行单元测试

python - 在 python 中处理错误的最有效方式是什么?

linux - 在 Linux 内核中使用断言