2010-02-19 24 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

他们似乎忘了更新的实际文档。

相关问题