I have a file data.xml
in src/test/resources/
.
How can I read that file into a new FileReader
in my test data.scala
Another alternative (especially if you need to access resource as a File
); is to obtain it's path via:
val path = getClass.getResource("/testData.txt").getPath
val file = new File(path)
as has been pointed out in Scala get file path of file in resources folder
And in cases where getClass.getResource
does not work (don't know nor care when or why exactly), com.google.common.io.Resources.getResource
from Google Guava usually does
testCompile "com.google.guava:guava:18.0"
To know where you are in file system during test, you can do something like this in a dummy test:
import scala.collection.JavaConversions._
for(file <- new File(".").listFiles ){
println(file.getAbsolutePath)
}
Then, when you know your path, in your test you can use it as:
new File("./src/test/resources/yourfile.xml")
Resources are meant to be accessed using the special getResource
style methods that Java provides. Given your example of data.xml
being in $SBT_PROJECT_HOME/src/test/resources/
, you can access it in a test like so:
import scala.io.Source
// The string argument given to getResource is a path relative to
// the resources directory.
val source = Source.fromURL(getClass.getResource("/data.xml"))
Of course that source
is now just a normal Scala IO object so you can do anything you want with it, like reading the contents and using it for test data.
There are other methods to get the resource as well (for example as a stream). For more information look at the getResource
methods on the Java Docs: Class.
sbt copies files from src/test/resources
to target/scala-[scalaVersion]/test-classes
.
You can access the resources in your tests as follows:
Source.fromURL(getClass.getResource("/testData.txt"))
It does assume that testData.txt
was directly under the folder src/test/resources
. Add any subdirectories, otherwise.