Access to test files

How to read files in tests if files are located in resource directory, jar, or in arbitrary place? When we write tests we may store files with test data in resource directory or in arbitrary place on the disk.

Problem

Files from resource directory will be included into result JAR file. It means that our test code should be able to read same file from directory and from JAR. When we run tests from IDEA, e.g. IntelliJ, files will be read from directory. But when we run tests like

sbt test

files will be read from JAR as resource file.

Solution

A solution is to use class Source with different creation function for each type of running tests.

/**
  * Returns a Source from specified file name.
  *
  * @param name specifies the file; it may be a file in resources and in JAR as well, or it may be any file
  * @return the Source from specified file name.
  */
def source(name: String): Try[Source] = {
  try {
    if (getClass.getClassLoader.getResourceAsStream(name) != null) {
      Try(Source.fromResource(name))
    } else {
      Try(Source.fromFile(name))
    }
  }
  catch {
    case e: Exception => Failure(e)
  }
}

You may see code with tests on Git

 

Advertisements

About ysden123

We are not only for work... All my time free from work I spend on photography. Most photos are from our travels. I like make photos in still life style as well.
This entry was posted in Programming, Scala and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s