Reputation: 63
I'm working on a small Gradle project and want to use my Reader
class in a Spock test. When I start the test the Reader
class throws:
java.nio.file.NoSuchFileException
In my Gradle project, I have test.txt
file in /src/test/resources
. When I run the test with my Reader
then Gradle shows me:
java.nio.file.NoSuchFileException: file:project_path/build/resources/test/test.txt
even though there is a file in that path. I checked using both the terminal and the browser.
I use Java 11 on Ubuntu.
//Reader class read lines:
try (Stream<String> stream = Files.lines(Path.of(String.valueOf(getClass().getClassLoader().getResource(fileName)))))
//gradle.build without test dependencies
apply plugin: "java"
apply plugin: "groovy"
group = "com.example"
version = "1.0"
sourceCompatibility = "1.11"
repositories {
mavenCentral()
}
Upvotes: 1
Views: 847
Reputation: 5031
Change your Reader
read logic on:
try (Stream<String> stream = Files.lines(Path.of(ClassLoader.getSystemResource(fileName).toURI()))) {
...
}
Path.of()
will create correct path when using URI: /project_path/build/resources/test/test.txt because it will extract path from the provider specified by the protocol in the URI (file: in your case).
But when you call Path.of()
for String
argument it assumes it is the real path (file:project_path/build/resources/test/test.txt in your case).
Upvotes: 1