如何在JUnit测试中检索Maven属性? [英] How to retrieve maven properties inside a JUnit test?

查看:65
本文介绍了如何在JUnit测试中检索Maven属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为文件解析器类编写测试. parse方法接收一个文件名作为参数,必须打开它才能对其进行解析(duh).

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

我已经编写了一个测试文件,并将其放入项目目录中的test/resources目录中,并希望将该文件传递给我以测试我的解析.由于该项目在CVS中,并且将由其他人操纵,因此我无法对文件路径进行硬编码,因此我考虑在测试中使用maven $ {basedir}属性构建文件名.像这样:

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?

推荐答案

您有2个选项:

1)通过系统属性(文档)

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

在pom中,您可以执行以下操作:

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)将文件放在src/test/resources中,与您的测试类位于同一软件包下.然后您可以使用Class.getResourceAsStream(String fileName)(

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

与选项1相比,我强烈建议使用选项2.通过系统属性将内容传递给测试非常麻烦,IMO.它将您的测试不必要地耦合到测试运行程序,并会在以后引起头痛.从类路径中加载文件是一种方法,这就是为什么maven具有资源目录的概念.

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.

这篇关于如何在JUnit测试中检索Maven属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆