How to retrieve maven properties inside a JUnit test?
Asked Answered
S

1

22

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?

Sofko answered 29/10, 2008 at 15:53 Comment(0)
M
28

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.

Melodeemelodeon answered 29/10, 2008 at 17:3 Comment(4)
I'll take the option 2. But as I want to pass the file name, instead of using the Class.getResourceAsStream( String fileName ) method, I'm using Class.getResource( String fileName ).getFile(). Thanks MikeSofko
That's cool. Just be aware that if you ever have to run the tests out of a JAR (which is unlikely) you might get some weird behavior.Melodeemelodeon
Not sure how complete this answer is - what about "integration test" properties like local DB address that you may want to store in your private settings.xml?Avrilavrit
<systemProperties> is deprecated. Use <systemPropertyVariables> instead.Claudeclaudel

© 2022 - 2024 — McMap. All rights reserved.