当前位置: 代码迷 >> Android >> Android 中的单元测试(运用ServiceTestCase 进行 Service测试 例子)
  详细解决方案

Android 中的单元测试(运用ServiceTestCase 进行 Service测试 例子)

热度:429   发布时间:2016-05-01 17:44:20.0
Android 中的单元测试(使用ServiceTestCase 进行 Service测试 例子)

进行Android Service 测试之前要稍微熟悉Android Service的生命周期,onCreate只执行一次,完了后是OnStart()。对于一个已经启动的Service来说,再次调用startService()只会执行OnStart()了。

首先我们写一个最简单的Service,建立一个project 叫 AndroidService:

src/com.waitingfy.android/AndroidService.java

package com.waitingfy.android;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.Log;public class AndroidService extends Service{ 	private final static String TAG = "AndroidService";	@Override	public void onCreate() {		super.onCreate();		Log.v(TAG, "service: onCreate()");	}	@Override	public void onStart(Intent intent, int startId) {		super.onStart(intent, startId);		Log.v(TAG, "service: onStart()");	}	@Override	public void onDestroy() {		super.onDestroy();		Log.v(TAG, "service: onDestroy()");	}	@Override	public IBinder onBind(Intent intent) {		// TODO Auto-generated method stub		return null;	}}

记得在AndroidManifest.xml中要注册这个服务

接下来我们建立一个AndroidTest的project基于上面我们刚刚建立的项目,名字叫 AndroidServiceTest

src/com.waitingfy.android.test/TestAndroidService.java

package com.waitingfy.android.test;import com.waitingfy.android.AndroidService;import android.content.Intent;import android.test.ServiceTestCase;import android.test.suitebuilder.annotation.SmallTest;public class TestAndroidService extends ServiceTestCase<AndroidService>{	public TestAndroidService() {		super(AndroidService.class);	}	    @Override	protected void setUp() throws Exception {		super.setUp();        getContext().startService(new Intent(getContext(), AndroidService.class));	}    @SmallTest    public void testSomething() {		assertEquals(2, 2);	}	@Override	protected void tearDown() throws Exception {		getContext().stopService(new Intent(getContext(), AndroidService.class));	}}


测试结果如下:

写在后面:

第一个弄的时候报了这个错误:

junit.framework.AssertionFailedError: Class com.waitingfy.android.test.TestAndroidService has no public constructor TestCase(String name) or TestCase()

是因为构造函数没有写对。

public TestAndroidService(Class<AndroidService> serviceClass) {		super(serviceClass);		// TODO Auto-generated constructor stub	}

改成

	public TestAndroidService() {		super(AndroidService.class);	}

就ok了。

源码下载: AndroidServiceTest.rar

文章源地址:http://www.waitingfy.com/?p=103

文章源地址:


  相关解决方案