0

Context and Justification

So I'm writing tests for a projects where the methods require JSON as input, but since there's no good way of writing inline JSON in Java, I want to include my test case JSON as a .json file that can be loaded when the tests are run. The most logical place for these JSON files is in the same directory as where the corresponding test belongs, so that the grouping of the tests and their JSON is clear. The only problem with this is that I can't find a good way to load in these JSON files without hard-coding their address. As such, the question follows:

Question

How can I programmatically determine the directory of the current Java file, so that I can then use that directory to load in files contained within it? Note that I don't want to find the current working directory of the program, since that may not match the directory where my tests are contained.

Thanks heaps!

Miguel Guthridge
  • 525
  • 4
  • 13
  • 1
    If you put your test files under src/test/resources they will be on the classpath (assuming you're using maven). You can structure them into packages to match your Java package layout. – tgdavies Nov 09 '21 at 06:02
  • 1
    There is no such context, as a Java *class* can be loaded from let's say a `byte[]` and have no associated directory (not address). In a maven project you would most likely use the `test/resources` folder, so your logical location is the wrong assumption. You could then use `Class.getResource()` or `Class.getResourceAsStream()` to access those. – Kayaman Nov 09 '21 at 06:02
  • Ok `test/resources` should work, since it seems that that's what's going on with Maven projects. Not sure if that's correct since the project configuration was mostly done through starter code which is beyond the scope of the course content (and TBH I want to stay as far away from Java as possible), but I'll give it a go :) – Miguel Guthridge Nov 09 '21 at 06:06

0 Answers0