在 Android Studio 中运行仪器测试而不模拟用户操作

问题描述

我已经编写了一些操作 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.*;

我如何运行此测试?

解决方法

我的错误如下。

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

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

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

因此,它仍然作为本地非仪器化测试运行。

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

之后Android studio提示我创建一个新的运行配置,测试运行成功。