2

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"
}
Community
  • 1
  • 1
sccrap
  • 23
  • 4
  • What do you mean by resource? You mean a file you added to the `/public` folder? Or some resource you can find based on the route you defined within the `routes`? – o-0 Sep 11 '18 at 05:04
  • In other words where is the `test.json` file? – o-0 Sep 11 '18 at 05:05
  • Possible duplicate of [How to access test resources?](https://stackoverflow.com/questions/5285898/how-to-access-test-resources) – mana Sep 11 '18 at 06:52

1 Answers1

2

Your project directory structure (Play Framework)

  • /
    • /app
    • /conf
    • /test
      • test.json
      • /controllers
        • HomeControllerSpec.scala

The reason why you cannot access test.json from /test

  • Any files other than '*.scala' in the source path (/app, /test) are excluded.
  • test.json in /test is excluded when compiled.

Alternative way

Put test.json in /test/resources

  • /
    • /app
    • /conf
    • /test
      • /resources
        • test.json
      • /controllers
        • HomeControllerSpec.scala

Read Also