【问题标题】:android test project does not find android-specific classandroid 测试项目没有找到 android-specific 类
【发布时间】:2014-01-06 17:09:18
【问题描述】:

简而言之:我有一个 android 项目(在 Eclipse 中)和一个测试项目。当我想使用 JUnit 执行测试方法(使用 android.location.Location)时,我得到了 android.location.Location 的 classNotFoundException。

更多细节:我有两个 Eclipse 项目

  • 我的应用程序
  • myAppTest

第二个是使用 Eclipse 向导为 Android 测试项目创建的,并且有一个清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.myApp.test"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <instrumentation
        android:name="android.test.InstrumentationTestRunner"
        android:targetPackage="com.myApp" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <uses-library android:name="android.test.runner" />
    </application>

</manifest>

我在项目 myApp 中有一个类 com.myApp.SomeClass 我想测试它的方法 someMethod(Location location)。因此,我将类 com.myApp.test.SomeClassTest 添加到 myAppTest 项目中,如下所示:

public class SomeClassTest {
    @Test
    public void testSomeMethod() {
        Location location = new Location("A");
        int result com.myApp.SomeClass.someMethod(location);
        //assert result here
    }
}

当我使用 Android JUnit 测试启动器将 testSomeMethod 作为 JUnit 测试执行时,我得到了异常: java.lang.NoClassDefFoundError: android/location/Location 在 com.myApp.test.SomeClassTest.testSomeMethod

我在创建测试项目时选择了 Android 4.2.2 作为构建目标(即包含 Android 4.2.2 库)。 (另外,我已经包含了 JUnit 4 库。)

如何避免异常?我不想启动任何 Android 模拟器,我只想执行一个普通的 JUnit 测试来测试包含 Android SDK 类(但甚至不是任何 GUI 类)的方法。

非常感谢您提前提供的任何帮助!

【问题讨论】:

  • 啊,顺便说一句:当 SomeClassTest 扩展 android.test.AndroidTestCase 并且我将测试方法作为 Android JUnit Test 运行以便模拟器启动时,我也得到了 NoClassFoundException。消息是“测试运行失败:因 'java.lang.ClassNotFoundException 而导致检测运行失败”
  • 在这一行,android:targetPackage="myApp",你应该使用整个包,比如:android:targetPackage="com.example.myApp.test"。看看它是否改变了什么。
  • 如果我使用 Eclipse JUnit 启动器在原始测试类中运行 testSomeMethod,我得到#A fatal error has been detected by the Java Runtime Environment: # # Internal Error (javaClasses.cpp:129), pid=24028, tid=140249730012928 # 致命错误:预加载类布局无效
  • @ErickFilho:感谢您的即时评论;-)“myApp”实际上是包(和项目名称)。我承认这是误导,我会解决它。但是,使用包 myApp.test 作为 targetPackage 不会改变任何东西。顺便问一下,targetPackage 是什么意思?
  • 看一下,developer.android.com/guide/topics/manifest/…,刚刚意识到我在那里错误地添加了 .test。

标签: java android eclipse unit-testing junit


【解决方案1】:

似乎正在尝试的事情(在不启动模拟器的情况下测试使用 Android API 的类)是不可能的。相反,我更改了 SomeClassTest 以扩展 AndroidTestCase,并且我选择了“Runs As Android JUnit Test”,它会启动模拟器。然后,一切正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-30
    • 2018-02-15
    • 2020-09-22
    • 1970-01-01
    • 2012-06-23
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    相关资源
    最近更新 更多