I have a project with multiple maven modules

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 access sample.json as

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());
}

so IFSClientTest runs fins since they are in same package.

Problem?
InventorySummaryResourceTest calls MockIFSClient which tries to access the same code, but now it fails as

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 has dependency as

<dependency>
    <groupId>com.org.project.external_services</groupId>
    <artifactId>ifs</artifactId>
    <version>${project.version}</version>
    <type>test-jar</type>
    <scope>test</scope>
</dependency>

Question

What change do I make to

new File(getClass().getResource("/getInventoryAndPriceResponse.json").getPath())

so that it can be accessed from different modules as well

有帮助吗?

解决方案

This answer helped me getting it right

How to really read text file from classpath in Java

I changed my code then to

inventoryPriceDetails = mapper.readValue(getClass().getResourceAsStream("/getInventoryAndPriceResponse.json"), new TypeReference<List<InventoryPriceDetail>>() {});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top