【问题标题】:How to access test resources in Scala?如何访问 Scala 中的测试资源?
【发布时间】:2011-07-14 05:48:08
【问题描述】:

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

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

【问题讨论】:

    标签: scala sbt


    【解决方案1】:

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

    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 对象,所以你可以用它做任何你想做的事情,比如读取内容并将其用于测试数据。

    还有其他方法可以获取资源(例如作为流)。有关更多信息,请查看 Java Docs: Class 上的 getResource 方法。

    【讨论】:

    • 我必须在指令中添加一个getClassLoader。结果是Source.fromURL(getClass.getClassLoader.getResource("simulation.json"))
    • 需要确认 Moebius 评论 getClassLoader。没有它,路径包括测试类的类层次目录。像~/lighthouse/target/scala-2.12/test-classes/com/mycompany/myapp/module1/utils/blabla/ 这样的东西。使用getClass.getClassLoader.getResource() 部分com/mycompany/myapp/module1/utils/blabla/ 被删除
    【解决方案2】:

    另一种选择(特别是如果您需要以File 访问资源);是通过以下方式获取它的路径:

    val path = getClass.getResource("/testData.txt").getPath
    val file = new File(path)
    

    正如Scala get file path of file in resources folder中指出的那样

    【讨论】:

      【解决方案3】:

      sbt 将文件从src/test/resources 复制到target/scala-[scalaVersion]/test-classes

      您可以按如下方式访问测试中的资源:

      Source.fromURL(getClass.getResource("/testData.txt"))
      

      它确实假定testData.txt 直接位于文件夹src/test/resources 下。添加任何子目录,否则。

      【讨论】:

        【解决方案4】:

        如果getClass.getResource 不起作用(不知道也不关心确切的时间或原因),来自 Google Guava 的 com.google.common.io.Resources.getResource 通常会起作用

        testCompile "com.google.guava:guava:18.0"
        

        【讨论】:

          【解决方案5】:

          要在测试期间了解您在文件系统中的位置,您可以在虚拟测试中执行以下操作:

           import scala.collection.JavaConversions._
            for(file <- new File(".").listFiles ){
             println(file.getAbsolutePath)
            }
          

          然后,当您知道自己的路径时,您可以在测试中将其用作:

          new File("./src/test/resources/yourfile.xml")
          

          【讨论】:

          • src/test/resources 下的文件位于 test 的 CLASSPATH 中,因此测试可以在代码不知道构建目录结构的情况下访问它。
          • 这可能很有用,如果需要枚举资源(即代码没有固定它们的名称,但会使用放置在其中的任何文件)。
          • 当您将应用部署为 fat jar 时,这会给您带来麻烦
          猜你喜欢
          • 2012-10-05
          • 1970-01-01
          • 2014-08-21
          • 2012-03-04
          • 2016-06-18
          • 1970-01-01
          • 2017-07-05
          • 1970-01-01
          • 2023-03-19
          相关资源
          最近更新 更多