I'm writing some jUnit tests that depend on data files. Where should those data files go? And how would I (in the jUnit tests) get the location of that directory?
In Python, I would use something similar to:
datadir = os.dirname(__file__) + "/data/"
You can create a @DataJpaTest and @Autowire your repository into it. For example: @RunWith(SpringRunner. class) @DataJpaTest public class MyJpaTest { @Autowired private ChartRepository chartRepository; @Test public void myTest() { ... } }
In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream . // the stream holding the file content InputStream is = getClass().
JUnit's Parameterized runner runs each and every test method with given data provider. In one test class, you can define several data providers as different static methods and use them in different test methods.
Kind of depends on what you're using the data files for, but in general, just create a package and make sure it's on your classpath. To load a properties file from the "data" package, add a "MyData.props" file and you can use load a properties file like:
this.getClass().getClassLoader().getResourceAsStream("/data/MyData.props");
Again, not exactly sure if this answers your question since I'm not 100% sure what you're trying to do, but I hope it helps a little.
Keep your test data close to your test classes (same package). As todd.run suggested, use getResourceAsStream()
to access your data files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With