Android ActivityInstrumentationT…


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

ActivityInstrumentationTestCase2 也支持:

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

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

Android ActivityInstrumentationTestCase2示例 - Smile宅 - Smile宅 

Focus2ActivityTest 的代码如下,用于测试Android ApiDemos示例解析(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 right of left button",

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

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

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

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

 }

  

 @MediumTest

 publicvoidtestGoingRightFromLeftButtonJumpsOverCenterToRight() {

 sendKeys(KeyEvent.KEYCODE_DPAD_RIGHT);

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

 }

  

 @MediumTest

 publicvoidtestGoingLeftFromRightButtonGoesToCenter()  {

  

 getActivity().runOnUiThread(newRunnable() {

 publicvoidrun() {

 mRightButton.requestFocus();

 }

 });

 // wait for the request to go through

 getInstrumentation().waitForIdleSync();

  

 assertTrue(mRightButton.isFocused());

  

 sendKeys(KeyEvent.KEYCODE_DPAD_LEFT);

 assertTrue("center button should be focused",

 mCenterButton.isFocused());

 }

}

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

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

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

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

 

转载于:https://my.oschina.net/zhangzhe/blog/414044

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值