Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
666 views
in Technique[技术] by (71.8m points)

sbt - How to access test resources in Scala?

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 in src/test/scala/?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...