问题
I have a project whose complete source you can find at its GitHub page here on the feat/config
branch. The problem I am having is that ClassName.class.getClassLoader().getResourceAsStream()
always returns null
, and creating a File
with the complete path (including the source directory) also returns a FileNotFoundException
.
This code should load the default configuration values out of a classpath resource and write it to a File
. It works locally but fails on Travis CI.
public static void writeDefault(String res, File out) throws IOException {
if (!out.exists()) {
out.getParentFile().mkdirs();
out.createNewFile();
}
OutputStream stream = new FileOutputStream(out);
InputStream in = FileConfig.class.getClassLoader().getResourceAsStream(res);
if (in == null) {
stream.close();
throw new FileNotFoundException(res);
}
IOUtils.copy(in, stream);
stream.close();
}
@Test
public void testFileConfig() throws IOException {
System.out.println("Creating default config file");
File testConfigFile = new File("configs/test.txt");
if (!testConfigFile.exists())
FileConfig.writeDefault("configs/test.txt", testConfigFile);
System.out.println("Loading config file");
Config testConfig = FileConfig.loadConfig(testConfigFile);
System.out.println("Loaded value: " + testConfig.getValue("value-1"));
System.out.println("Deleting config file");
testConfigFile.deleteOnExit();
}
The above test fails with the following stack trace:
jtrial.config.TestConfig > testFileConfig STANDARD_OUT
Creating default config file
jtrial.config.TestConfig > testFileConfig FAILED
java.io.FileNotFoundException: configs/test.txt
at jtrial.config.FileConfig.writeDefault(FileConfig.java:111)
at jtrial.config.TestConfig.testFileConfig(TestConfig.java:24)
.travis.yml
config file:
language: java
jdk:
- oraclejdk8
notifications:
email: false
install:
- chmod +x ./gradlew
- ./gradlew --info assemble
script: ./gradlew --info check
回答1:
Ahem... PREPARE TO CRINGE AND FACEPALM!
I just realized... that... I had configs/
on the .gitignore
file. This wasn't only ignoring the configs/
directory in the root project directory, but every instance of configs/
. I just replaced it with ./configs/
and then ACTUALLY added the text files to a new commit. *facepalms to a new dimension*
回答2:
I think that your problem is caused by this Gradle issue: src/test/resources not added to classpath intermittently.
来源:https://stackoverflow.com/questions/37636089/travis-ci-and-junit-with-gradle-cannot-find-classpath-resources