gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 23:14:33 25 4
gpt4 key购买 nike

我正在尝试测试模块中的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com