0

我已经编写了一些操作 MotionEvent 实例的代码,并想为它编写一个单元测试。

单元测试只需要验证我的操作;它不需要模拟任何用户操作。

我知道它需要是一个仪器测试才能使用 MotionEvent 的方法;我需要实际的方法,而不是任何嘲笑。

我在目录 src/androidTest/... 中定义了一个检测测试;但是,它仍然抛出异常

java.lang.RuntimeException:在 android.view.MotionEvent 中获取的方法未模拟。

我的模块 build.gradle 文件包含以下条目:

defaultConfig {
    ...
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
...
dependencies {
    implementation 'androidx.appcompat:appcompat:1.3.0'
    implementation 'com.google.android.material:material:1.3.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}

我的测试类中的导入如下:

import android.view.MotionEvent;
import org.junit.Test;
import static org.junit.Assert.*;

我怎样才能运行这个测试?

4

1 回答 1

0

我的错误如下。

我最初认为本地单元测试就足够了,因为不涉及用户操作。

结果证明是错误的:本地单元测试无法访问 Android 方法。

我将包含测试的文件移动到为仪器测试指定的位置 /src/androidTest/java/,但没有更改文件;这可以在我的导入中看到。

出于这个原因,它仍然作为本地非仪器测试运行。

意识到这一点后,我更改了文件以模​​仿 Android Studio 与我的项目一起创建的 ExampleInstrumentedTest。我还删除了仍然是本地测试的运行配置。

之后安卓工作室提示我新建一个运行配置,测试运行成功。

于 2021-07-01T18:16:17.383 回答