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

网友投稿 360 2022-09-16

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{ 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 serviceClass) { super(serviceClass); // TODO Auto-generated constructor stub }

改成

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

就ok了。

源码下载:​​ AndroidServiceTest.rar​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Android 中的单元测试 (普通Java类中的Function测试篇)
下一篇:C++ 基础之
相关文章

 发表评论

暂时没有评论,来抢沙发吧~