Android测试教程(12):ServiceTestCase示例

jerry Android 2015年08月24日 收藏

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 的代碼如下:

  1. public class LocalServiceTest
  2. extends ServiceTestCase<LocalService> {
  3.  
  4. public LocalServiceTest() {
  5. super(LocalService.class);
  6. }
  7.  
  8. @Override
  9. protected void setUp() throws Exception {
  10. super.setUp();
  11. }
  12.  
  13. @SmallTest
  14. public void testPreconditions() {
  15. }
  16.  
  17. /**
  18. * Test basic startup/shutdown of Service
  19. */
  20. @SmallTest
  21. public void testStartable() {
  22. Intent startIntent = new Intent();
  23. startIntent.setClass(getContext(), LocalService.class);
  24. startService(startIntent);
  25. }
  26.  
  27. /**
  28. * Test binding to service
  29. */
  30. @MediumTest
  31. public void testBindable() {
  32. Intent startIntent = new Intent();
  33. startIntent.setClass(getContext(), LocalService.class);
  34. IBinder service = bindService(startIntent);
  35. }
  36.  
  37. }

testStartable 測試對應的Service能否正常啟動。

testBindable 測試對應的Service能否綁定成功