Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve maven properties inside a JUnit test?

Tags:

I'm writing a test for a file parser class. The parse method receives a file name as parameter, and must open it in order to parse it ( duh ).

I've writen a test file, that I put into the test/resources directory inside my project directory, and would like to pass this file to test my parse. Since this project is in CVS, and will be manipulated by others, I can't hard code the file path, so I thought about use the maven ${basedir} property to build the file name in my test. Something like:

public void parseTest() {     ...     sut.parse( ${basedir} + "src/test/resources/testFile" );     ... } 

Does someone knows how could I achieve this?

like image 626
Alexandre Avatar asked Oct 29 '08 15:10

Alexandre


People also ask

How does maven integrate with JUnit?

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.

How read Pom properties file in java?

Use the properties-maven-plugin to write specific pom properties to a file at compile time, and then read that file at run time.

How do I pass system properties in Maven?

To provide System Properties to the tests from command line, you just need to configure maven surefire plugin and use -D{systemproperty}={propertyvalue} parameter in commandline. Run Single Test with Maven : $ mvn test -Dtest=MessageUtilTest#msg_add_test -Dmy_message="Hello, Developer!"


1 Answers

You have 2 options:

1) Pass the file path to your test via a system property (docs)

In your pom you could do something like:

<project>   [...]   <build>     <plugins>       <plugin>         <groupId>org.apache.maven.plugins</groupId>         <artifactId>maven-surefire-plugin</artifactId>         <version>2.4.2</version>         <configuration>           <systemProperties>             <property>               <name>filePath</name>               <value>/path/to/the/file</value>             </property>           </systemProperties>         </configuration>       </plugin>     </plugins>   </build>   [...] </project> 

Then in your test you can do:

System.getProperty("filePath"); 

2) Put the file inside src/test/resources under the same package as your test class. Then you can get to the file using Class.getResourceAsStream(String fileName) (docs).

I would highly recommend option 2 over option 1. Passing things to your tests via system properties is very dirty IMO. It couples your tests unnecessarily to the test runner and will cause headaches down the road. Loading the file off the classpath is the way to go and that's why maven has the concept of a resources directory.

like image 104
Mike Deck Avatar answered Sep 20 '22 20:09

Mike Deck