tags:

views:

1085

answers:

1

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?

+7  A: 

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.

Mike Deck
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 Mike
Alexandre
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.
Mike Deck