I am having a problems running the following code:
configService.setMainConfig("src/test/resources/MainConfig.xml");
From within a Junit @Before method.
Is this the way Maven builds out its target folder?
File class to read the /src/test/resources directory by calling the getAbsolutePath() method: String path = "src/test/resources"; File file = new File(path); String absolutePath = file. getAbsolutePath(); System. out.
Using Java getResourceAsStream() This is an example of using getResourceAsStream method to read a file from src/main/resources directory. First, we are using the getResourceAsStream method to create an instance of InputStream. Next, we create an instance of InputStreamReader for the input stream.
We can run our unit tests with Maven by using the command: mvn clean test. When we run this command at command prompt, we should see that the Maven Surefire Plugin runs our unit tests. We can now create a Maven project that compiles and runs unit tests which use JUnit 5.
Access MainConfig.xml
directly. The src/test/resources
directory contents are placed in the root of your CLASSPATH.
More precisely: contents of src/test/resources
are copied into target/test-classes
, so if you have the following project structure:
. └── src └── test ├── java │ └── foo │ └── C.java └── resources ├── a.xml └── foo └── b.xml
It will result with the following test CLASSPATH contents:
/foo/C.class
/a.xml
/foo/b.xml
To actually access the files from Java source, use getClass().getResource("/MainConfig.xml").getFile()
.
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