谷歌文档部分翻译:JUnit4 Rules with the ATSL

android的测试支持库为AndroidJUnitRunner提供了junit规则支持库,为测试的时候提供了便利。
类似于ActivityInstrumentationTestCase2或者ServiceTestCase都是已经被谷歌弃用了,与之对应替代的事ActivityTestRule和ServiceTestRule(TestCases变成TestRule了)
ActivityTestRule
这个规则提供了测试单个activity的能力,这个activity会在@Test之前启动,并且在每个方法的@Before之前调用。它会在测试结束和@After方法完成之后结束。那么想要调用这个activity实例的话只需要调用ActivityTestRule#getActivity()方法。(此处的意思是没一个测试方法调用之前之后可以选择关闭这个activity或者不关闭)
这里给出了一个例子:

@RunWith(AndroidJUnit4.class)
@LargeTest
public class MyClassTest {

    @Rule
    public ActivityTestRule<MyClass> mActivityRule = new ActivityTestRule(MyClass.class);

    @Test
    public void myClassMethod_ReturnsTrue() { ... }
}

ServiceTestRule
这个规则提供了一个简单的方法在你测试的时候去启动和关闭你的服务。它也保证了连接或绑定的时候这个服务连接成功。这个服务会自动在测试完成的时候停止掉。要注意的是,这个规则不支持IntentService。
于是又有个例子:

@RunWith(AndroidJUnit4.class)
@MediumTest
public class MyServiceTest {

    @Rule
    public final ServiceTestRule mServiceRule = new ServiceTestRule();

    @Test
    public void testWithStartedService() {
        mServiceRule.startService(
            new Intent(InstrumentationRegistry.getTargetContext(), MyService.class));
        // test code
    }

    @Test
    public void testWithBoundService() {
        IBinder binder = mServiceRule.bindService(
            new Intent(InstrumentationRegistry.getTargetContext(), MyService.class));
        MyService service = ((MyService.LocalBinder) binder).getService();
        assertTrue("True wasn't returned", service.doSomethingToReturnTrue());
    }
}

robotium的官网:
https://github.com/RobotiumTech/robotium

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值