如何访问 Scala 中的测试资源? [英] How to access test resources in Scala?

查看:37
本文介绍了如何访问 Scala 中的测试资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 src/test/resources/ 中有一个文件 data.xml.

I have a file data.xml in src/test/resources/.

如何在 src/test/scala/ 中的测试 data.scala 中将该文件读入新的 FileReader 中?

How can I read that file into a new FileReader in my test data.scala in src/test/scala/?

推荐答案

资源旨在使用 Java 提供的特殊 getResource 样式方法进行访问.鉴于 data.xml$SBT_PROJECT_HOME/src/test/resources/ 中的示例,您可以像这样在测试中访问它:

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"))

当然,source 现在只是一个普通的 Scala IO 对象,所以你可以用它做任何你想做的事情,比如读取内容并将其用于测试数据.

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.

还有其他方法可以获取资源(例如作为流).有关详细信息,请查看 getResource 方法rel="noreferrer">Java 文档:类.

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.

这篇关于如何访问 Scala 中的测试资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆