4

I'm using the following call to get a stream so that I can find the filenames of some of my resources.

Thread.currentThread().getContextClassLoader().getResourceAsStream(...)

This works fine when I run my code normally, and it also works fine if I duplicate my resources into my test folder.

How do I avoid this duplication and make my tests (when run through IDEA) use the resources from main?

NQA
  • 315
  • 1
  • 3
  • 11
  • I found a maven specific workaround. Check this out: http://stackoverflow.com/a/6541151/451518 – default locale Feb 16 '17 at 08:33
  • @defaultlocale Thanks. I'm not sure I understand that comment though. And I've updated the question to make it clear that I just want to run the tests normally through IntelliJ IDEA. (Though I will also want them to work with Maven later I guess.) – NQA Feb 16 '17 at 09:01

1 Answers1

7

Everything you have in src/test/resources is copied by maven-resources-plugin into target/test-classes. Then, everything you have in src/main/resources goes into target/classes. Then, maven-surefire-plugin configures classpath in this order: target/test-classes first and target/classes next.

Thanks to that, if your resource stays both in src/main/resources and src/test/resources, its "test" version will be loaded in the unit test.

If it only exists in the src/main/resources, it will be available in the unit test, without any further actions.

If it exists in src/test/resources only, you will have an ability to access it only during unit testing.

yegor256
  • 102,010
  • 123
  • 446
  • 597
  • Thanks for the reply Yegor. Everything you say appears to be true and yet it's still not working for some reason. I might be missing something silly though, so I'll keep looking. – NQA Feb 16 '17 at 11:47
  • Came across this comment: http://stackoverflow.com/questions/3923129/get-a-list-of-resources-from-classpath-directory/3923685#comment67155595_3923685. It seems that if there are class files in the test folder then it doesn't list the non-class files that I am interested in. If I put the non-class files in their own folder then it picks them up. Bit weird. – NQA Feb 16 '17 at 13:45