ServiceTestCase 为测试Service提供了一个可控的测试环境,它提供对Service 生命周期的基本支持,并可以通过注入一些依赖对象来控制测试环境以便测试Service。
ServiceTestCase的类继承如下图所示:
Service Lifecycle 支持, 每个Service运行 都遵循一定的顺序(生命周期方法),ServiceTestCase提供下面方法来支持对Service生命周期方法的测试:
- 每个测试方法调用之前首先会执行setUp 方法,setUp 的基本实现是取得系统Context ,如果你要重载setUp 的话,注意在第一行加上super.setUp.
- 在调用startService(Intent) 或bindService(Intent) 之后,ServiceTestCase才会调用Service的onCreate 方法,从而使你有机会在Service启动之前对测试环境做些调整。
- 当你的测试方法调用startService(Intent) 或bindService(Intent) 之后,ServiceTestCase 调用Service 的onCreate 方法,然后再调用Service相应的 startService(Intent)或 service 的bindService(Intent, ServiceConnection, int)方法。并保存用于tracking 和支持Lifecycle 对应的值。
- 每个测试方法结束后,调用tearDown 方法,这个方法stop 并destroy 被测试的service. 如果你需要重载tearDown, 注意先调用super.tearDown.
Dependency Injection 每个Service都依赖于运行它的Context 对象和Application 对象,ServiceTestCase 测试框架允许你注入这些对象(修改过,Mocked等)以实现真正的单元测试.
LocalServiceTest 的代码如下:
public class LocalServiceTest extends ServiceTestCase<LocalService> { public LocalServiceTest() { super(LocalService.class); } @Override protected void setUp() throws Exception { super.setUp(); } @SmallTest public void testPreconditions() { } /** * Test basic startup/shutdown of Service */ @SmallTest public void testStartable() { Intent startIntent = new Intent(); startIntent.setClass(getContext(), LocalService.class); startService(startIntent); } /** * Test binding to service */ @MediumTest public void testBindable() { Intent startIntent = new Intent(); startIntent.setClass(getContext(), LocalService.class); IBinder service = bindService(startIntent); } }
testStartable 测试对应的Service能否正常启动。
testBindable 测试对应的Service能否绑定成功