Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add custom resource directory to test classpath without copying the files inside?

Tags:

sbt

When I run my tests, the contents of my special resources directory special-resources are copied to the target/classes directory. I have something like this

unmanagedResourceDirectories in Compile += baseDirectory.value / "special-resources",

But I do not want to copy these resources into the target directory, but I want them to be on the classpath of forked java processes (e.g. for testing).

I have tried using

unmanagedClasspath in Compile += baseDirectory.value / "special-resources",

but the resources are not available.

How can I add a resource directory to the classpath without having to copy the files? Or, alternatively, how can I setup sbt to not copy resources to the target directory?

like image 364
fommil Avatar asked Aug 06 '14 11:08

fommil


Video Answer


1 Answers

To have the contents of the special-resources directory included in the classpath for tests and runMain task, do the following:

unmanagedClasspath in Test += baseDirectory.value / "special-resources"

unmanagedClasspath in (Compile, runMain) += baseDirectory.value / "special-resources"

Check that the setting is set properly with show:

> show test:unmanagedClasspath
[info] List(Attributed(C:\dev\sandbox\runtime-assembly\special-resources))

With the following Specs2 tests I'm convinced the setup worked fine:

import org.specs2.mutable._

class HelloWorldSpec extends Specification {

  "Hello world" should {
    "find the file on classpath" in {
      val text = io.Source.fromInputStream(getClass.getResourceAsStream("hello.txt")).mkString
      text must have size(11)
    }
  }
}

hello.txt is in the special-resources directory with a hello world string inside.

> ; clean ; test
[success] Total time: 0 s, completed 2014-08-06 20:00:02
[info] Updating {file:/C:/dev/sandbox/runtime-assembly/}runtime-assembly...
[info] Resolving org.jacoco#org.jacoco.agent;0.7.1.201405082137 ...
[info] Done updating.
[info] Compiling 1 Scala source to C:\dev\sandbox\runtime-assembly\target\scala-2.10\test-classes...
[info] HelloWorldSpec
[info]
[info] Hello world should
[info] + find the file on classpath
[info]
[info] Total for specification HelloWorldSpec
[info] Finished in 17 ms
[info] 1 example, 0 failure, 0 error
[info] Passed: Total 1, Failed 0, Errors 0, Passed 1

And build.sbt:

unmanagedClasspath in Test += baseDirectory.value / "special-resources"

libraryDependencies += "org.specs2" %% "specs2" % "2.4" % "test"

fork in Test := true
like image 95
Jacek Laskowski Avatar answered Sep 23 '22 18:09

Jacek Laskowski