junit test:配置文件,其路径变量为资源

时间:2016-05-10 09:17:39

标签: java file testing junit configuration

我有一个AttributesLoader类,用于选择配置文件,检索变量并将其设置为对象。

示例:

   if (validatePropertyValue(configuration.getString(PROPERTY_RECORD_LIMIT))) {
                extractionAttributesBuilder.setRecordLimit(configuration.getInt(PROPERTY_RECORD_LIMIT));
            }

代码工作正常,但我很难为某些属性编写测试。 因为代码选择了一个文件,所以我的src / test / resources中有一个cfg文件。 其中一个属性是目录的路径..

我试过这样做:

path=new File(AttributesLoaderTest.class.getResource("/extractPath").getPath()));

但它不起作用,因为它寻找路径: new File(AttributesLoaderTest.class.getResource(" / extractPath")。getPath()));这是没用的..

我的问题是:

如何在文件中将路径提供给我的src / test / resources目录而不进行硬化处理?

path=/extractPath

1 个答案:

答案 0 :(得分:0)

一个选项可以是将root作为系统属性传递,并使用它来组成文件的路径。

pom.xml中,您可以设置系统属性,如下所示:

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <configuration>
      <systemPropertyVariables>
        <resourcesDirectory>${project.build.directory}/src/config/</resourcesDirectory>
        [...]
      </systemPropertyVariables>
    </configuration>
  </plugin>

然后在JUnit类中你可以拥有:

path=new File(AttributesLoaderTest.class.getResource(System.getProperty("resourcesDirectory") + "/extractPath").getPath()));    

注意:尚未测试上面的代码,因此可能包含一些错误。

相关问题