Android ActivityInstrumentationT…

来源:互联网 发布:数据库冷备份怎么恢复 编辑:程序博客网 时间:2024/05/18 01:46


ActivityInstrumentationTestCase2 用来测试单个的Activity,被测试的Activity可以使用InstrumentationTestCase.launchActivity 来启动,然后你能够直接操作被测试的Activity

ActivityInstrumentationTestCase2 也支持:

  • 可以在UI线程中运行测试方法.
  • 可以注入Intent对象到被测试的Activity

ActivityInstrumentationTestCase2 取代之前的ActivityInstrumentationTestCase ,新的测试应该使用ActivityInstrumentationTestCase2作为基类。

Android ActivityInstrumentationTestCase2示例 - Smile宅 - Smile宅 

Focus2ActivityTest 的代码如下,用于测试AndroidApiDemos示例解析(116):Views->Focus->2.Horizontal

 

 

publicclassFocus2ActivityTest

 extendsActivityInstrumentationTestCase2<Focus2>{

  

 privateButton mLeftButton;

 privateButton mCenterButton;

 privateButton mRightButton;

  

 publicFocus2ActivityTest() {

 super("com.example.android.apis",Focus2.class);

 }

  

 @Override

 protectedvoidsetUp() throwsException{

 super.setUp();

 finalFocus2 a = getActivity();

 mLeftButton = (Button)a.findViewById(R.id.leftButton);

 mCenterButton = (Button)a.findViewById(R.id.centerButton);

 mRightButton = (Button)a.findViewById(R.id.rightButton);

 }

  

 @MediumTest

 publicvoidtestPreconditions(){

 assertTrue("center button should be rightof left button",

 mLeftButton.getRight() <mCenterButton.getLeft());

 assertTrue("right button should be rightof center button",

 mCenterButton.getRight() <mRightButton.getLeft());

 assertTrue("left button should befocused", mLeftButton.isFocused());

 }

  

 @MediumTest

 publicvoidtestGoingRightFromLeftButtonJumpsOverCenterToRight(){

 sendKeys(KeyEvent.KEYCODE_DPAD_RIGHT);

 assertTrue("right button should befocused", mRightButton.isFocused());

 }

  

 @MediumTest

 publicvoidtestGoingLeftFromRightButtonGoesToCenter() {

  

 getActivity().runOnUiThread(newRunnable(){

 publicvoidrun() {

 mRightButton.requestFocus();

 }

 });

 // wait for the request to gothrough

 getInstrumentation().waitForIdleSync();

  

 assertTrue(mRightButton.isFocused());

  

 sendKeys(KeyEvent.KEYCODE_DPAD_LEFT);

 assertTrue("center button should befocused",

 mCenterButton.isFocused());

 }

}

setUp 中初始化mLeftButtonmCenterButtonmRightButton,调用每个测试方法之前,setUp都会被调用。

testPreconditions 通常为第一个测试方法,用来检测后续的测试环境是否符合条件。

testGoingRightFromLeftButtonJumpsOverCenterToRight中调用sendKeys可以模拟按键消息。

testGoingLeftFromRightButtonGoesToCenter ,使用runOnUiThread 来为mRightButton请求focus,使用runOnUiThread 的原因是因为本测试方法不在UI线程中运行。  getInstrumentation 可以取得Instrumentation对象,有了Instrumentation 对象就可以对Activity进行大部分的操作,waitForIdleSync()等待application回到idle状态,之后就可以检测mRightButton是否获得了焦点。

 

0 0