我有一个包含多个maven模块的项目
project/pom.xml
/external_services/pom.xml
/ifs/pom.xml
/src/test/java/
/MockIFSClient.java
/IFSClientTest.java
/src/test/java/resources/sample.json
/inventory/pom.xml
/business/pom.xml
/src/main/java/InventorySummary.java
/services/pom.xml
/src/main/java/InventorySummaryResource.java
/src/main/test/InventorySummaryResourceTest.java
MockIFSClient 以
的身份访问sample.json
try {
inventoryPriceDetails = mapper.readValue(new File(getClass().getResource("/getInventoryAndPriceResponse.json").getPath()), new TypeReference<List<InventoryPriceDetail>>() {
});
} catch (final IOException e) {
throw new RuntimeException("could not read resource :" + e.getMessage());
}
所以 IFSClientTest 会运行fins,因为它们位于同一个包中。
问题吗
InventorySummaryResourceTest
调用MockIFSClient
尝试访问相同的代码,但现在它失败了
could not read resource :file:/Users/harith/IdeaProjects/inventory_api/external_services/ifs/target/ifs-1.0-SNAPSHOT-tests.jar!/sample.json (No such file or directory)
services / pom.xml 具有依赖性
<dependency>
<groupId>com.org.project.external_services</groupId>
<artifactId>ifs</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
问题
我对
做了什么改变new File(getClass().getResource("/getInventoryAndPriceResponse.json").getPath())
以便可以从不同的模块访问
答案 0 :(得分:3)
这个答案帮助我做对了
How to really read text file from classpath in Java
我将代码更改为
inventoryPriceDetails = mapper.readValue(getClass().getResourceAsStream("/getInventoryAndPriceResponse.json"), new TypeReference<List<InventoryPriceDetail>>() {});