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能否綁定成功