2010-02-19 28 views
5

我想在android上構建一個有效的junit測試套件。ServiceTestCase <T> .getService?

由於我是Junit的新手,我無法弄清楚如何使用ServiceTestCase類。

我無法弄清楚如何讓getService()方法起作用。它永遠返回null。所以我決定通過startService啓動它。這是行不通的。

你能幫我嗎?

感謝

+1

如果有人回答你的問題,習慣上點擊他們答案旁邊的複選標記。這樣做會幫助你更快地獲得更好的答案。 –

回答

16

這是你需要測試你的服務

public class MyServiceTests extends ServiceTestCase<MyService> { 

private static final String TAG = "MyServiceTests"; 

public MyServiceTests() { 
    super(MyService.class); 
} 

/** 
* Test basic startup/shutdown of Service 
*/ 
@SmallTest 
public void testStartable() { 
    Intent startIntent = new Intent(); 
    startIntent.setClass(getContext(), MyService.class); 
    startService(startIntent); 
    assertNotNull(getService()); 
} 

/** 
* Test binding to service 
*/ 
@MediumTest 
public void testBindable() { 
    Intent startIntent = new Intent(); 
    startIntent.setClass(getContext(), MyService.class); 
    IBinder service = bindService(startIntent); 
    assertNotNull(service); 
} 
} 

我已經寫了關於Android的測試和測試驅動開發一些文章,你會發現有用的東西,檢查http://dtmilano.blogspot.com/search/label/test%20driven%20development

+0

非常感謝。 –

+0

很好的答案仍然@dtmilano。你在android測試上的工作非常有趣。 – Snicolas

+0

在測試服務之前,您是否真的必須先運行您的應用程序(啓動服務)?我想單獨運行你的服務測試,但得到startIntent變量的NullPointerException。 –

0

接受的答案不再適用。

的TestCase像ActivityInstrumentationTestCase2或ServiceTestCase被 棄用,取而代之的ActivityTestRule或ServiceTestRule的。

ATSL link

他們似乎忘了更新的實際文檔。

相關問題