ServiceTestCase 為測試Service提供了一個可控的測試環境,它提供對Service 生命周期的基本支持,並可以通過注入一些依賴對象來控制測試環境以便測試Service。
ServiceTestCase的類繼承如下圖所示:
Service Lifecycle 支持, 每個Service運行 都遵循一定的順序(生命周期方法),ServiceTestCase提供下面方法來支持對Service生命周期方法的測試:
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能否綁定成功