ServiceTestCase 為測(cè)試 Service 提供了一個(gè)可控的測(cè)試環(huán)境,它提供對(duì) Service 生命周期的基本支持,並可以通過注入一些依賴對(duì)象來控制測(cè)試環(huán)境以便測(cè)試 Service。
ServiceTestCase 的類繼承如下圖所示:
http://wiki.jikexueyuan.com/project/android-test-course/images/12.1.jpg" alt="picture12.1" />
Service Lifecycle 支持, 每個(gè) Service 運(yùn)行 都遵循一定的順序(生命周期方法),ServiceTestCase 提供下面方法來支持對(duì) Service 生命周期方法的測(cè)試:
Dependency Injection 每個(gè) Service 都依賴於運(yùn)行它的 Context 對(duì)象和 Application 對(duì)象,ServiceTestCase 測(cè)試框架允許你注入這些對(duì)象(修改過,Mocked 等)以實(shí)現(xiàn)真正的單元測(cè)試.
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 測(cè)試對(duì)應(yīng)的 Service 能否正常啟動(dòng)。
testBindable 測(cè)試對(duì)應(yīng)的 Service 能否綁定成功