How to fork the jvm for each test in sbt

2020-04-02 08:04发布

问题:

I am working with some classes that (for some reason) can only be used once within a single VM. My test cases work if I run them individually (fork := true) enabled in my sbt settings.

If I run more than one of these tests, they fail with an exception that has to with a thread executor rejecting a task (it's most likely closed). It would be very time consuming to find out what causes the problem and even if I find the problem, I might not be able to resolve it (I do not have access to the source code).

I am currently using the specs2 test framework, but any test framework using sbt would be acceptable.

Is there any test framework for sbt that is capable of running each test in a jvm fork?

Thoughts or ideas on possible other solutions are of course welcome.

回答1:

It turns out this is fairly easy to achieve. The documentation is sufficient and can be found at Testing - Forking tests

// Define a method to group tests, in my case a single test per group
def singleTests(tests: Seq[TestDefinition]) =
  tests map { test =>
    new Group(
      name = test.name,
      tests = Seq(test),
      runPolicy = SubProcess(javaOptions = Seq.empty[String]))
  }

// Add the following to the `Project` settings
testGrouping in Test <<= definedTests in Test map singleTests


回答2:

Using non-deprecated syntax:

testGrouping in Test := (definedTests in Test).value map { test =>
  Tests.Group(name = test.name, tests = Seq(test), runPolicy = Tests.SubProcess(
    ForkOptions(
      javaHome.value,
      outputStrategy.value,
      Nil,
      Some(baseDirectory.value),
      javaOptions.value,
      connectInput.value,
      envVars.value
    )))
}


标签: scala sbt