what is a resource? a resource is a file in the class path folder structure for your project. this is important because your test resources will be put in your test-classes folder hierarchy and your main resources will be put in your classes folder hierarchy — both in your target folder.
File class to read the /src/test/resources directory by calling the getAbsolutePath() method: String path = "src/test/resources"; File file = new File(path); String absolutePath = file. getAbsolutePath(); System.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With