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