Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test data directory with jUnit

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/"
like image 797
David Wolever Avatar asked Mar 23 '09 18:03

David Wolever


People also ask

How do you write a JUnit test case for a repository?

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() { ... } }

How do I read a file from test Resources folder?

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().

Does JUnit have data provider?

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.


2 Answers

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.

like image 61
Todd R Avatar answered Oct 19 '22 23:10

Todd R


Keep your test data close to your test classes (same package). As todd.run suggested, use getResourceAsStream() to access your data files.

like image 40
trunkc Avatar answered Oct 20 '22 01:10

trunkc