Android測試教程(12):ServiceTestCase樣本

來源:互聯網
上載者:User

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

查看全套教程:http://www.bianceng.cn/OS/extra/201301/35252.htm

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.