Question
I could not find how to include resources in test code with Play Framework.
I want to write getResource code @/test/controllers/HomeControllerSpec.scala as follows.
"HomeController Test" should {
val inputStream = getClass.getResourceAsStream("test.json")
...
}
But this code require that "test.json" is placed in target directory. I found a way to use Inject and play.api.Environment but this method do not work well in test code.
Getting a resource file as an InputStream in Playframework
Are there any best practice to read resources in test code?
Additional Information
I tried the following code @ /play/test/controllers/HomeControllerSpec.scala
val source = getClass.getResource("/").getPath
println(source.toString())
And I also got the following result (/play is the root of play project).
/play/target/scala-2.12/test-classes/
Generally, /target is ignored (written in .gitignore). So I want to know the way to read text files in Play test code (placed in /test).
Solution (solved. Thanks your comments and help.)
I tried the following command
sbt "show test:resourceDirectory"
and got the following result.
/play/test/resources
This means that files placed in this directory are used as resources and copied to target directory (/play/target/scala-2.12/test-classes in my case). So I put the test.json at
/play/test/resources/test.json
and could read this file by the following code.
val source = getClass.getResource("/test.json").getPath
val code = getClass.getResourceAsStream("/test.json")
println("getPath of test.json: "+ source)
println("text of test.json: " + IOUtils.toString(code))
Output
getPath of test.json: /play/target/scala-2.12/test-
classes/test.json
text of test.json: {
"key": "value"
}