5

ボタンを含む簡単なアクティビティがあります。ボタンを押すと、2番目のアクティビティが実行されます。今、私はAndroidInstrumentationTestingを初めて使用します。これまでのところ、これは私が書いたものです

public class TestSplashActivity extends
    ActivityInstrumentationTestCase2<ActivitySplashScreen> {

private Button mLeftButton;
private ActivitySplashScreen activitySplashScreen;
private ActivityMonitor childMonitor = null;
public TestSplashActivity() {
    super(ActivitySplashScreen.class);
}

@Override
protected void setUp() throws Exception {
    super.setUp();
    final ActivitySplashScreen a = getActivity();
    assertNotNull(a);
    activitySplashScreen=a;
    mLeftButton=(Button) a.findViewById(R.id.btn1);

}

@SmallTest
public void testNameOfButton(){
    assertEquals("Press Me", mLeftButton.getText().toString());
    this.childMonitor = new ActivityMonitor(SecondActivity.class.getName(), null, true);
    this.getInstrumentation().addMonitor(childMonitor);
    activitySplashScreen.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            mLeftButton.performClick();
    }});

    Activity childActivity=this.getInstrumentation().waitForMonitorWithTimeout(childMonitor, 5000);
    assertEquals(childActivity, SecondActivity.class);

}

}

これで、ボタンのテキストを取得する最初のアサーションが機能します。しかし、実行クリックを呼び出すと、例外が発生します

  Only the original thread that created a view hierarchy can touch its views. 

これで、Androidアプリケーションのコンテキストではこの例外を理解できましたが、インストルメンテーションテストの観点からは理解できました。ボタンのクリックイベントを実行するにはどうすればよいですか。また、2番目のアクティビティが読み込まれたかどうかを確認するにはどうすればよいですか。

4

1 に答える 1

4

InstrumentationTestCaseを拡張するテストクラスがあり、テストメソッドを使用しているとすると、次のロジックに従う必要があります。

  1. チェックしたいアクティビティへの関心を登録します。
  2. それを起動します
  3. あなたがそれでやりたいことをしてください。コンポーネントが正しいかどうかを確認し、ユーザーアクションを実行します。
  4. 「シーケンス」の次のアクティビティへの関心を登録します
  5. シーケンスの次のアクティビティをポップアップさせるそのアクティビティのアクションを実行します。
  6. このロジックに従って、繰り返します...

コードに関しては、これは次のような結果になります。

Instrumentation mInstrumentation = getInstrumentation();
// We register our interest in the activity
Instrumentation.ActivityMonitor monitor = mInstrumentation.addMonitor(YourClass.class.getName(), null, false);
// We launch it
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClassName(mInstrumentation.getTargetContext(), YourClass.class.getName());
mInstrumentation.startActivitySync(intent);

Activity currentActivity = getInstrumentation().waitForMonitor(monitor);
assertNotNull(currentActivity);
// We register our interest in the next activity from the sequence in this use case
mInstrumentation.removeMonitor(monitor);
monitor = mInstrumentation.addMonitor(YourNextClass.class.getName(), null, false);

クリックを送信するには、次のようにします。

View v = currentActivity.findViewById(....R.id...);
assertNotNull(v);
TouchUtils.clickView(this, v);
mInstrumentation.sendStringSync("Some text to send into that view, if it would be a text view for example. If it would be a button it would already have been clicked by now.");
于 2013-03-17T13:24:32.600 に答える