http://www.touch3g.cn/html/y2009/using-junit-in-android-app-development-1236.htm

本文介绍在Android 1.5中集成JUnit进行测试的方法。包括如何配置测试项目、运行测试案例,并提供了三种执行单元测试的方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这几天忙着写一个Android App(等完成以后应该会open source),今天差不多把网络相关的部分实现了,XML解析还有待完善。几天没写blog感觉有点不自在,正好想起Android 1.5_r1的release notes中专门提到了ADT0.9对于JUnit支持的改进,对于崇尚TDD(测试驱动开发)的人来说这无疑是一个好消息,今天就抽点时间说说Android 1.5中JUnit集成相关的要点吧。 配置完1.5的SDKADT0.9,运行第一个1.5的sample的时候我就看到Run as中多出了一个 “Android JUnit Test”的选项(以前是在Debug中)。
[img]http://www.touch3g.cn/wp-content/uploads/2009/05/runas_junit_test.png[/img]

可是文档里并没有提到如何在Android project中集成JUnit测试,好在我从Android Developers讨论组里找到了TDD with Android 1.5这么一个帖子。 就先来看一看如何把Sample中的test case跑起来吧。 (多谢Zhao的blog上关于在Android 1.5 pre中运行APIDemo测试的总结) 第1步,新建一个Android项目,选择“create project from existing source”,并把路径指向android-sdk-1.5/platforms/android-1.5/samples/ApiDemos 第2步,再新建一个Android项目,依然通过“create project from existing source”的方式,这次把路径指向android-sdk-1.5/platforms/android-1.5/samples/ApiDemos/tests 这时候ADT会报错,因为它无法找到APIDemo项目。右键,选择Properties,在Java Build Path –> Projects中添加APIDemo项目即可。 第3步,以“Android Application”方式运行第一个项目(注意正确设置AVD),APIDemo将被安装到模拟器。 第4步,以“Android Application”方式运行第二个项目(注意正确设置AVD),APIDemo Test将被安装到模拟器。 第5步,现在,我们可以通过Dev Tools中的Instrumentation来执行APIDemo Test了。找到Instrumentation中的”Tests for API Demos.”,点击即可开始测试。 这时,通过LogCat即可看到测试结果。 除了通过Dev Tools来执行单元测试,我们还有另外两种方法: 1、通过ADT,在eclipse中执行测试 在eclipse中选中test项目,直接Run As “Android JUnit Test”既可以,测试结果会以图形化的方式返回。

[img]http://www.touch3g.cn/wp-content/uploads/2009/05/instrumentation_apidemo.png[/img]

[img]http://www.touch3g.cn/wp-content/uploads/2009/05/logcat_instrumentation.png[/img]
[img]http://www.touch3g.cn/wp-content/uploads/2009/05/android-junit.png[/img]

2、通过sdb shell命令执行测试
在命令行中执行 adb shell am instrument -w com.example.android.apis.tests/android.test.InstrumentationTestRunner 命令
测试结果如下:

[img]http://www.touch3g.cn/wp-content/uploads/2009/05/unittest_through_adbshell-300x84.png[/img]

其中,com.example.android.apis.tests是APIDemo Test所在的package。

那么,我们如何创建自己的test项目呢?
大致的步骤如下:
1、新建一个普通的Android项目,比如项目名为Foo,Package为com.foo.bar
2、新建一个Test项目,注意把Package填成com.foo.bar.tests,项目名任意,比如FooTest,Application name任意
3、在FooTest项目的Build Path中添加Foo项目
4、参照APIDemo Test项目的manifext.xml来修改FooTest项目的manifest.xml
5、编写TestCase(至于测试代码的编写,William也还在学习中 :))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值