Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Can't I access src/test/resources in Junit test run with Maven?

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?

like image 937
Michael W Avatar asked Sep 30 '11 16:09

Michael W


People also ask

How do I get SRC test resources?

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.

How do I read a file from SRC main resources?

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.

How do I run a JUnit project in Maven?

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.


1 Answers

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

like image 133
Tomasz Nurkiewicz Avatar answered Oct 23 '22 12:10

Tomasz Nurkiewicz