2013-03-17 168 views
3

我有一個簡單的活動,其中包含一個按鈕。當我按下按鈕時,第二個活動運行。現在我是Android Instrumentation Testing的新手。到目前爲止,這是我寫Android儀器啓動活動

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

假設你有延伸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."); 
+0

在我的應用程序中,點擊按鈕啓動新的活動。我想測試這種情況,如果第二個活動啓動或沒有,我點擊一個按鈕後?我如何測試這種情況? – user1730789 2013-03-17 13:36:31

+0

我已編輯的問題將我的部分代碼。 – user1730789 2013-03-17 14:05:44

+0

我明白了。不要發送那樣的點擊。您應該使用檢測類發送點擊。我編輯了我的帖子。 – 2013-03-17 14:50:38