【发布时间】:2014-02-24 15:38:14
【问题描述】:
我觉得在如何使用 JUnit 测试 Android 库项目方面存在很多困惑。
我将描述到目前为止我遇到的所有错误(为了其他程序员也尝试这样做),最后我将说明我的最后一个和当前的问题。
-
1234563 JUnit 测试
所以你肯定需要为测试创建一个新项目,关注this guide
注意:尽管指南告诉您使用TestCase及其派生类AndroidTestCase,但有几篇帖子似乎指出TestCase仅用于 JUnit3 测试,JUnit4 测试不扩展任何类。
我不知道当你想运行一个使用 Android API 的测试时我应该使用什么,如果你想在 JUnit4 下使用它,我还没有达到那个地步。对于不使用 Android API 的测试,请使用 JUnit4 样式类。如果您只遵循指南,您的测试将在运行时失败“Invalid layout of ... at value”。这是因为运行配置在其 classpath 中包含 Android。转到测试的 JUnit 测试运行配置(右键单击测试->属性->运行/调试设置->编辑)并从 classPath boostrap 条目中删除 Android。
编辑
首次运行测试时,在Eclipse中,如果选择Android启动器,则必须选择使用“Eclipse JUnit Launcher”或“Android JUnit Test Launcher”的启动器,无需删除引导条目。从现在开始我没有成功。对于使用 Android API 的测试,扩展
AndroidTestCase。这些测试需要更长的时间才能启动,它们需要运行模拟器,即使您不是在测试应用程序本身,而是在测试一个没有与用户接口的实用程序类。要运行 Android UNIT 案例测试,启动器会查找库目标项目所没有的目标包 APK 文件。
当您按照 #2 中的指南进行操作时,目标包已自动插入到您的测试项目的清单中。测试项目的清单应如下所示:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.Common.lib.test" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="14" /> <instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="com.Common.lib" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <uses-library android:name="android.test.runner" /> </application> </manifest>
这里的目标包是我要测试的库。给出了一个解决方案in this post 将测试项目用作具有APK的应用程序。所以现在我把目标包从
android:targetPackage="com.Common.lib" />
到
android:targetPackage="com.Common.lib.test" />
但启动器仍在寻找库 APK,即使我在测试项目中添加了库作为参考,请参阅下面的 logcat(注意 CommonLibTest.apk 已成功加载):
[2014-02-24 16:17:50 - CommonLibTest] Dx trouble writing output: already prepared [2014-02-24 16:17:51 - CommonLibTest] ------------------------------ [2014-02-24 16:17:51 - CommonLibTest] Android Launch! [2014-02-24 16:17:51 - CommonLibTest] adb is running normally. [2014-02-24 16:17:51 - CommonLibTest] Performing android.test.InstrumentationTestRunner JUnit launch [2014-02-24 16:17:51 - CommonLibTest] Automatic Target Mode: using existing emulator 'emulator-5554' running compatible AVD 'Phone-x86-jb' [2014-02-24 16:17:51 - CommonLibTest] Uploading CommonLibTest.apk onto device 'emulator-5554' [2014-02-24 16:17:52 - CommonLibTest] Installing CommonLibTest.apk... [2014-02-24 16:17:52 - CommonLibTest] Success! [2014-02-24 16:17:52 - CommonLib] Could not find CommonLib.apk! [2014-02-24 16:17:52 - CommonLibTest] Launching instrumentation android.test.InstrumentationTestRunner on emulator-5554 [2014-02-24 16:17:53 - CommonLibTest] Test run failed: Instrumentation run failed due to 'java.lang.ClassNotFoundException'
这是我所知道的。
如果想相信有人已经用 JUnit 成功地测试了一个库项目并且已经解决了我的问题。
【问题讨论】:
标签: android eclipse unit-testing junit junit4