问题
我找不到如何使用 Play Framework 在测试代码中包含资源。
我想编写 getResource 代码@/test/controllers/HomeControllerSpec.scala,如下所示。
"HomeController Test" should {
val inputStream = getClass.getResourceAsStream("test.json")
...
}
但是此代码要求将“test.json”放置在目标目录中。 我找到了一种使用 Inject 和 play.api.Environment 的方法,但此方法在测试代码中效果不佳。
Getting a resource file as an InputStream in Playframework
是否有读取测试代码中资源的最佳实践?
其他信息
我尝试了以下代码@/play/test/controllers/HomeControllerSpec.scala
val source = getClass.getResource("/").getPath
println(source.toString())
我还得到了以下结果(/play是play项目的根目录)。
/play/target/scala-2.12/test-classes/
通常,/target 会被忽略(写在 .gitignore 中)。所以我想知道Play测试代码(放在/test中)读取文本文件的方式。
解决方案(已解决。感谢您的评论和帮助。)
我尝试了以下命令
sbt "show test:resourceDirectory"
得到以下结果。
/play/test/resources
这意味着放置在该目录中的文件将用作资源并复制到目标目录(在我的例子中为/play/target/scala-2.12/test-classes)。所以我把 test.json 放在
/play/test/resources/test.json
并且可以通过以下代码读取该文件。
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))
输出
getPath of test.json: /play/target/scala-2.12/test-
classes/test.json
text of test.json: {
"key": "value"
}
最佳答案
您的项目目录结构(Play Framework)
- /
- /应用程序
- /conf
- /测试
- 测试.json
- / Controller
- HomeControllerSpec.scala
无法从/test
访问test.json
的原因
- 源路径(
/app
、/test
)中除“*.scala”之外的任何文件都将被排除。
编译时排除 test.json
。
/test
中的替代方式
将test.json
放入/test/resources
- /
- /应用程序
- /conf
- /测试
- /资源
- 测试.json
- / Controller
- HomeControllerSpec.scala
- /资源
另请阅读
关于scala - 如何使用Play Framework读取测试代码中的资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52268681/