I am writing a test using the Groovy Spock framework, IntelliJ and Bazel build system. The goal is to read test data from LamborghiniAventador.obj
located in the same directory as the test file, Model3dImporterSpec.groovy
.
I am getting a java.io.FileNotFoundException
.
def "reading from test file in same directory"() {
given: "some stuff"
//do some stuff here
when: "reading from test file"
def file = Paths.get("LamborghiniAventador.obj").normalize().toFile()
def byteArray = getFileAsByteStream(file.getAbsolutePath())
then: "file should be read and byte array should not be null"
byteArray != null;
}
private static byte[] getFileAsByteStream(String pathToFile) {
return new File(pathToFile).text.getBytes()
}
The path to my file when I search on command line is: ~/Dev/Master/src/test/java/com/censored/api/editor/model3dparsers/LamborghiniAventador.obj
I can successfully read from a file sitting on my desktop but as soon as I relocate that file within the project space things stop working.
How do I read test data from a test file, where the test data file and the test file live in the same directory. This is an easy task in Java (Eclipse). I have looked at a ton of other Stackoverflow questions to no avail so I think I have a serious lack of understanding here. I would love explanation in addition to an answer.
Edited for Clarification
I have solved my own question with help from @Opal.
1) When you want to access a resource in bazel you need to update the build file by adding in a resources array:
resources = ["LamborghiniAventador.obj"],
2) def foo = getClass().getResourceAsStream('LamborghiniAventador.obj')
as suggested by @Opal worked for me once I made change 1). So the code above is now:
def "reading a file in goovy."() {
when: "reading file from same directory"
System.out.println("Going to read from a file in same directory")
def foo = getClass().getResourceAsStream('LamborghiniAventador.obj')
def byteArray = foo.getBytes()
then: "file should be read and byte array should not be null"
byteArray != null;
}