我正在构建一个 android 应用程序,我想使用 JUnit 测试对其进行单元测试,而不是 Android JUnit 测试(因为使用模拟器运行 Android 测试需要很长时间)。
环境:
- eclipse
- 安卓项目
- Android测试项目(目标包=android项目包)
- JUnit4/Mockito
- 使用 JUnit 运行单元测试(故意不 Android JUnit)
只要测试自己编写的类,不依赖于Android类,一切顺利。但是当我想为包含例如Log.i()
语句或引用 TextView
,然后我遇到以下错误:
java.lang.NoClassDefFoundError: android/text/TextWatcher at java.lang.ClassLoader.defineClass1(Native Method)
Android 应用 list :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cleancode.lifesaver"
android:versionCode="1"
android:versionName="1.0" >
Android 测试项目 list :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cleancode.lifesaver.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<instrumentation
android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.cleancode.lifesaver" />
要测试的类:
import android.widget.TextView;
public class CapCharacterTextValidator extends TextValidator {
public CapCharacterTextValidator(TextView textView) {
super(textView);
}
@Override
public void validate(TextView textView, String text) {
}
}
测试类:
import org.junit.Test;
import com.cleancode.lifesaver.utils.CapCharacterTextValidator;
public class CapCharactersTextValidatorTests {
@Test
public void validateCharacters() {
new CapCharacterTextValidator(null);
}
}
我尝试在 Android 应用程序和 Android 测试应用程序或两者之一的导出库中添加 android 库,但仍然没有给我绿色测试。无论我尝试什么,我都会遇到此 NoClassDefFoundError
。
我阅读了大部分 android 文档,但他们似乎真的很喜欢在模拟器上使用 Android JUnit 的方法(对我来说太慢了)。
以下问答帖子也对我没有进一步帮助:
- Android JUnit testing ClassNotFoundException
- java.lang.NoClassDefFoundError while running JUnit test in Netbeans
- Eclipse + Android + JUnit test references android.os class = NoClassDefFoundError
如有任何帮助,我们将不胜感激!
最佳答案
要在单元测试中运行任何依赖于 Android 框架的东西,您必须使用 Android 测试运行器。没有别的办法。框架必须存在。
关于java - Android - 单元测试无法引用 Android 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18836411/