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

Karate特征文件及Spring Boot中资源文件访问方式咨询

1. 从test/java/karate目录下的Karate特征文件访问test/resources内的文件

Karate默认会将test/resources目录纳入类路径,直接通过以下两种方式访问即可:

  • 直接使用相对路径:若目标文件为test/resources/data.json,在特征文件中调用read('data.json')即可读取
  • 用classpath:前缀明确指定:read('classpath:data.json')
    如果文件在子目录(比如test/resources/json/user.json),则写read('json/user.json')或read('classpath:json/user.json')
2. Spring Boot中classpath为app/test/java时访问resources内的JSON文件

首先需确保resources目录(通常是src/test/resources或自定义路径的resources目录)被正确添加到类路径中,之后可通过以下方法访问:

  • 使用ResourceLoader注入读取:
    @Autowired
    private ResourceLoader resourceLoader;
    
    public String loadJsonFile() throws IOException {
        Resource resource = resourceLoader.getResource("classpath:data.json");
        return FileUtils.readFileToString(resource.getFile(), StandardCharsets.UTF_8);
    }
    
  • 直接实例化ClassPathResource读取:
    public String loadJson() throws IOException {
        ClassPathResource resource = new ClassPathResource("data.json");
        return new String(Files.readAllBytes(resource.getFile().toPath()));
    }
    

若使用Maven构建,可通过配置pom.xml确保资源目录被纳入类路径:

<build>
    <testResources>
        <testResource>
            <directory>app/test/resources</directory> <!-- 对应你的resources路径 -->
        </testResource>
    </testResources>
</build>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 13:30:56