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

IntelliJ IDEA 2022.1无法读取test/resources子目录文件求助

单元测试无法读取src/test/resources资源文件的解决方案

问题背景

Windows 11系统搭配IntelliJ IDEA 2022.1(社区版),运行单元测试时无法读取src/test/resources目录下的资源文件,该代码在Eclipse中可正常运行,排除代码逻辑问题。

已尝试的无效操作

  • 右键resources目录,先取消标记为资源根,再重新标记为测试资源根
  • 在模块设置中添加所需文件夹作为模块依赖

读取文件的Java代码

private static final String basePath = "src/test/resources/data/";

private static final ObjectMapper objectMapper;

static {
    objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
    objectMapper.findAndRegisterModules();
    objectMapper.registerModule(new JavaTimeModule());
}

public static <T> T getObjectFromFile(String relativePath, Class<T> clazz) {
    try {
        return objectMapper.readValue(new File(basePath + relativePath), clazz);
    } catch (IOException e) {
        log.error("Error while parsing JSON: {},{}", relativePath, e);
        return null;
    }
}

报错信息

10:02:32.107 [main] ERROR com.sams.ng.oms.payment.processor.util.ParserUtil - Error while parsing JSON: response/Response.json,java.io.FileNotFoundException: src\test\resources\data\response\Response.json (The system cannot find the path specified)

相关截图

  • 测试配置截图:测试配置截图
  • 目录结构截图:目录结构截图

可行解决方案

1. 改用类加载器读取资源(核心解决思路)

IDEA运行测试时的工作目录并非src/test/resources,直接用File类读取相对路径会导致找不到文件。改用类加载器获取资源流,修改后的代码如下:

public static <T> T getObjectFromFile(String relativePath, Class<T> clazz) {
    // 去掉src/test/resources前缀,直接从类路径根目录读取
    try (InputStream inputStream = ParserUtil.class.getClassLoader().getResourceAsStream("data/" + relativePath)) {
        if (inputStream == null) {
            log.error("Resource not found: data/{}", relativePath);
            return null;
        }
        return objectMapper.readValue(inputStream, clazz);
    } catch (IOException e) {
        log.error("Error while parsing JSON: {},{}", relativePath, e);
        return null;
    }
}

说明:src/test/resources下的文件会被编译到测试类路径的根目录,因此直接使用data/xxx即可定位到目标文件。

2. 检查并重置测试编译输出目录

  • 打开File > Project Structure > Modules,选中对应模块后切换到Paths标签
  • 确认Test output path是否为out/test/classes(默认路径),若路径异常,点击Reset to Default恢复
  • 执行Build > Rebuild Project后重新运行测试

3. 修正运行配置的工作目录

  • 点击右上角运行按钮旁的下拉箭头,选择Edit Configurations
  • 找到对应的JUnit配置项,查看Working directory设置,确保其为项目根目录(默认值为$MODULE_DIR$,若不是则手动修改为项目根路径)

4. 清理IDEA缓存并重启

  • 执行File > Invalidate Caches...,选择Invalidate and Restart
  • 缓存清理完成后重新运行测试

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 00:21:27