You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中JUnit5单元测试报错‘Test Events were not received’排查

Android Studio单元测试报错“Test Events were not received”排查方案

问题背景

我需要测试一个移除字符串特殊字符的函数,待测试的sanitize方法属于AddTeam类,代码如下:

public String sanitize(String string) {
    String regex = "[^a-zA-Z0-9\\s]";
    return string.replaceAll(regex, "");
}

对应的测试类AddTeamTest代码如下:

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

public class AddTeamTest {
    @Test
    public void sanitize() {
        AddTeam team = new AddTeam();
        String input1 = "abc123";
        String expected1 = "abc123";
        assertEquals(expected1, team.sanitize(input1));
    }
}

每次运行测试时,Android Studio都会报错Test Events were not received,尝试过重建项目、同步Gradle文件,问题仍未解决。

可能的原因及解决步骤

1. 核对JUnit 5依赖配置

确保Module级别的build.gradle文件中正确引入JUnit 5相关依赖:

dependencies {
    // 本地单元测试依赖
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.2'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.2'
    // 仪器化测试依赖(若需在设备上运行)
    androidTestImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.2'
    androidTestRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.2'
}

同时在gradle.properties中添加开启JUnit 5的配置:

android.testInstrumentationRunnerArguments.junit.jupiter.enabled=true

2. 确认测试类存放路径

  • 本地单元测试(JVM运行)必须放在src/test/java/目录下
  • 仪器化测试(设备/模拟器运行)必须放在src/androidTest/java/目录下
    路径错误会导致IDE无法识别测试类。

3. 检查测试运行配置

  • 打开Run Configuration,确认测试运行器选择的是JUnit 5
  • 确保配置中正确指定了测试类或方法的路径

4. 清理IDE缓存并重启

点击File -> Invalidate Caches... -> 选择Invalidate and Restart,彻底清除Android Studio缓存后重试。

5. 验证目标类的访问权限

确认AddTeam类和sanitize方法均为public权限,否则测试类无法实例化类或调用方法。

6. 通过Gradle命令运行测试

在终端执行以下命令,排查是否为IDE层面问题:

# 运行本地单元测试
./gradlew testDebugUnitTest
# 运行仪器化测试
./gradlew connectedDebugAndroidTest

如果命令行能正常执行测试,说明是IDE配置问题,可尝试更新Android Studio版本或重新导入项目。

内容的提问来源于stack exchange,提问作者Allen Klare

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 18:16:24