源码下载(免下载积分):下载
简述:测试Service使用的是ServiceTestCase,测试service的android 测试框架可以让service运行
在孤立的环境中,并提供了mock对象。当调用ServiceTestCase.startService()或者
ServiceTestCase.bindService()时,才会初始化测试环境,因此你可以在启动前,
设置自己的mock对象。
怎么设置mock Application和mock Context()呢?
设置mock Application通过setApplication()方法,设置mock Context通过setContext()方法
使用ServiceTestCase进行测试:
1. 继承
ServiceTestCase
public class LocalServiceTest extends
ServiceTestCase<LocalService>{
2. 增加构造函数,
public LocalServiceTest() {
super(LocalService.class);
/*
* ServiceTestCase 假设你将会使用mock context
*或者mock Application对于测试环境,如果不提供
*这些对象,当启动service时,ServiceTestcase会
*使用它自己的内部的实例去注入到service中,
*/
setContext(new MockContext());
setApplication(new MockApplication());
}
3. 增加setUp()方法和setupService()(基本上此方法不需要覆盖)方法
/*在每个测试方法之前执行,用于清除先前的测试,
*和变量的初始化
*/
@Override
protected void setUp() throws Exception {
// TODO Auto-generated method stub
super.setUp();
}
/*
*在测试中创建Service并注入所有的依赖(context application)
*当调用startService(Intent)或者bindService(Intent)时会自动
*调用这个方法,因此使用setContext()或者setApplication()注入
*依赖时,必须在这个方法之前
*/
@Override
protected void setupService() {
// TODO Auto-generated method stub
super.setupService();
}
4. 测试Service是否能
通过startService()来开启服务
//测试LocalService是否能够通过startService()来开启服务
public void testLocalServiceStartable()
{
Intent startIntent = new Intent();
startIntent.setClass(getContext(), LocalService.class);
startService(startIntent);
//返回在startService()或者bindService()或创建的service
LocalService localService = getService();
assertNotNull(localService);
assertEquals(LocalService.class.getName(),
localService.getClass().getName());
}
5. 测试Service能否被绑定
//验证LocalService能否被绑定
public void testLocalServiceBindable()
{
Intent bindIntent = new Intent();
bindIntent.setClass(getContext(), LocalService.class);
IBinder service = bindService(bindIntent);
//测试IBinder
assertNotNull(service);
}
6. 增加测试
tearDown()测试方法(这个方法可以不覆盖)
//这个方法会调用shutdownService()关闭所有的service
@Override
protected void tearDown() throws Exception {
// TODO Auto-generated method stub
super.tearDown();
}
}
这个例子没有先验的测试方法。
API中有一个service测试的开发者指导很不错,是这样说的:
1. Lifecycle Support : Service的函数有特定的调用顺序,为了支持Service的生命周期
ServiceTestCase必须遵守下列协议:
setUp()方法会在每个测试方法之前调用,如果覆盖这个方法,必须
保证第一条语句是super.setUp()
测试用例在测试方法中startService(Intent) or bindService(Intent)
后才会调用service的onCreate()方法来实例化service,因此在测试之前,
你有机会去调整测试框架和测试逻辑
当测试方法调用ServiceTestCase.startService()orServiceTestCase.bindService() ,
测试用例将会调用Service.onCreate(),然后调用Service.startService(Intent) or
Service.bindService(Intent, ServiceConnection, int),
当测试方法都结束后,测试用例会调用tearDown()方法,这个方法会停止,
销毁service根据service的启动方式,你必须在最后一条语句调用super.tearDown()
2. Dependency Injection:service有两个固有的依赖关系,它的Contex和相关的Application,
ServiceTestCase框架允许注入替代的mock的相关的依赖,因此,
执行单元测试,是在一个孤立的环境控制来依赖关系的。
原文:http://blog.csdn.net/wangfei199101/article/details/24196639