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.


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.


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) {
    } else {
  catch {
    case e: Exception => Failure(e)

You may see code with tests on Git



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: Logo

You are commenting using your 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 )

Connecting to %s