Reputation: 18712
I have two Maven projects A and B. B depends on A.
In A, I have a file someFile.txt
in the src/main/resources
folder.
public class SomeAClass
{
public void someMethod()
{
final InputStream inputStream =
Thread.currentThread()
.getContextClassLoader()
.getResourceAsStream("someFile.txt");
final List<String> lines = IOUtils.readLines(inputStream);
...
}
}
In A's tests, this works fine.
Now imagine I want to use that same code in B, including the ability to read the data from src/main/resources/someFile.txt
.
Right now, calling SomeAClass.someMethod()
from project B causes a NullPointerException and I suspect it's because src/main/resources/someFile.txt
cannot be found.
How can I change the code for getting the input stream for src/main/resources/someFile.txt
so that it works both in A's unit tests and when executing B (B is a Spring Shell based console application) ?
Upvotes: 2
Views: 5476
Reputation: 4115
Are you sure that the problem is there, because I have a similar approach and it works right.
That was my first attempt
If you are using someFile.txt as a resource in your tests (and only there, if you are using in your main project, ignore the post), instead of using src/main/resources
, maybe it would be better to put that file and others which are used in src/test/resources
.
But
If you put these test files in src/test/resources
, remember that the test resources are not contained in the project artifact, so you can not access them althoug you include the dependency in your pom.
What I did (something like yours)
Create new module (test-resources) and put the resources in src/main/resources
. The module is used as dependency in the projects I need with test scope. But what I used was ClassPathResource.
ClassPathResource resource = new ClassPathResource("the_file");
resource.getInputStream()
Upvotes: 5