Это похоже на такой глупый вопрос, но никакие решения, которые я нашел в Интернете, не работали для меня. Я пишу интеграционный тест в проекте Maven, и мне нужно прочитать значения из файла свойств, который я поместил в src/test/resources
.Чтение файла свойств в тесте Maven
Мой тест пытается прочитать файл этих свойств в процессе строительства:
public ControllerIT() throws Exception {
wc = new WebConversation();
prop = new Properties();
InputStream stream = getClass().getResourceAsStream("/test.properties");
prop.load(stream);
}
Когда я запускаю тест, я всегда получаю NullPointerException
на призыв к prop.load(stream);
.
Я попытался как раз о каждой перестановки решений, которые я нашел в Интернете:
- REFERENCING файл как
test.properties
вместо/test.properties
- Получение входного потока через
getClass().getClassLoader().getResourceAsStream("test.properties");
Но ничего не работает.
И я думаю, для дополнительных очков, идеальное решение позволит мне запустить этот тест через mvn integration-test
на CLI, а также в Eclipse, с помощью Run As
->JUnit test
. С этой целью, я думаю, я должен также упомянуть, что я явно добавил main/test/resources
в качестве исходной папки в Eclipse, но он по-прежнему не загружает файл правильно.
И в соответствии с просьбой, вот мой POM:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>listener-testing</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<name>listener-testing</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<!-- Failsafe configuration for running integration tests -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.16</version>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<!-- Surefire configuration for generating reports -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-report-plugin</artifactId>
<version>2.16</version>
<reportSets>
<reportSet>
<id>integration-tests</id>
<reports>
<report>failsafe-report-only </report>
</reports>
</reportSet>
</reportSets>
</plugin>
</plugins>
</reporting>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>httpunit</groupId>
<artifactId>httpunit</artifactId>
<version>1.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.x</version>
</dependency>
</dependencies>
</project>
Как вы можете видеть, это автономный тест интеграции люкс (в основном он только отправляет POST запросы к веб-службе). Я запустить его с mvn verify
и посмотреть:
$ mvn verify
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building listener-testing
[INFO] task-segment: [verify]
[INFO] ------------------------------------------------------------------------
[INFO] [site:attach-descriptor {execution: default-attach-descriptor}]
Downloading: http://artifactory:8081/artifactory/simple/vm/junit/junit/debian/junit- debian.pom
[INFO] Unable to find resource 'junit:junit:pom:debian' in repository libs-release (http://artifactory:8081/artifactory/libs-release)
Downloading: http://artifactory:8081/artifactory/simple/vm/junit/junit/debian/junit-debian.pom
[INFO] Unable to find resource 'junit:junit:pom:debian' in repository central (http://repo1.maven.org/maven2)
[INFO] [failsafe:integration-test {execution: default}]
[INFO] Failsafe report directory: /home/jmp/desktop/listener-testing/target/failsafe-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.example.integration.ControllerIT
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.156 sec <<< FAILURE! - in com.example.integration.ControllerIT
testRequest(com.example.integration.ControllerIT) Time elapsed: 0.006 sec <<< ERROR!
java.lang.NullPointerException: null
at java.util.Properties$LineReader.readLine(Properties.java:435)
at java.util.Properties.load0(Properties.java:354)
at java.util.Properties.load(Properties.java:342)
at com.example.integration.ControllerIT.<init> (ControllerIT.java:30)
Results :
Tests in error:
ControllerIT.<init>:30 » NullPointer
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] [failsafe:verify {execution: default}]
[INFO] Failsafe report directory: /home/jmp/desktop/listener-testing/target/failsafe-reports
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] There are test failures.
Please refer to /home/jmp/desktop/listener-testing/target/failsafe-reports for the individual test results.
[INFO] ------------------------------------------------------------------------
[INFO] For more information, run Maven with the -e switch
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2 seconds
[INFO] Finished at: Fri Mar 14 10:13:04 GMT 2014
[INFO] Final Memory: 12M/125M
[INFO] ------------------------------------------------------------------------
В этом выводе, строка 30 из ControllerIT
является призыв к prop.load(inputstream)
.
Пожалуйста, покажите свой полный файл pom и местоположение файла свойств toue. Как начать интеграционные тесты? Используете ли вы 'mvn verify'? – khmarbaise
Добавлен вывод POM и maven. – jpappe
Казалось, что это связано с этим: '[INFO] Невозможно найти ресурс 'junit: junit: pom: debian' в репозитории libs-release (http: // artifactory: 8081/artifactory/libs-release) Скачивание: http : // artifactory: 8081/artifactory/simple/vm/junit/junit/debian/junit-debian.pom'? – khmarbaise