How to access test resources in Scala?

后端 未结 5 875
难免孤独
难免孤独 2020-12-04 07:58

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

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

相关标签:
5条回答
  • 2020-12-04 08:26

    Another alternative (especially if you need to access resource as a File); is to obtain it's path via:

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

    as has been pointed out in Scala get file path of file in resources folder

    0 讨论(0)
  • 2020-12-04 08:31

    And in cases where getClass.getResource does not work (don't know nor care when or why exactly), com.google.common.io.Resources.getResource from Google Guava usually does

    testCompile "com.google.guava:guava:18.0"
    
    0 讨论(0)
  • 2020-12-04 08:35

    To know where you are in file system during test, you can do something like this in a dummy test:

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

    Then, when you know your path, in your test you can use it as:

    new File("./src/test/resources/yourfile.xml")
    
    0 讨论(0)
  • 2020-12-04 08:39

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

    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.

    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.

    0 讨论(0)
  • 2020-12-04 08:52

    sbt copies files from src/test/resources to target/scala-[scalaVersion]/test-classes.

    You can access the resources in your tests as follows:

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

    It does assume that testData.txt was directly under the folder src/test/resources. Add any subdirectories, otherwise.

    0 讨论(0)
提交回复
热议问题