20

モジュール内のアクティビティをテストしようとしています。テストメソッドでこのアクティビティを開始しようとしていますが、常にAssertionFailedError. この問題について Web を検索しましたが、解決策が見つかりませんでした。どんな助けでも大歓迎です。

これは私のテストクラスです:

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)

よろしく。

4

1 に答える 1

12

ActivityUnitTestCase のstartActivity()メソッドは、メイン スレッドでのみ呼び出す必要があります。

これは、次の方法で行うことができます。

  1. テスト メソッドの前に@UiThreadTestアノテーションを使用します。

    @UiThreadTest
    public void testWebViewHasNotSetBuiltInZoomControls() throws Exception {
        Intent intent = new Intent(getInstrumentation().getTargetContext(),
                ContactActivity.class);
        startActivity(intent, null, null);
    }
    
  2. 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);
               }
            });
     }
    

なぜ私は正しいのですか?

于 2015-04-20T12:27:52.357 に答える