2013-03-17 169 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