Supplying ScalaTest config map entries via the environment

(, en)

Supplying dynamic config settings to ScalaTest tests can be cumbersome. So how can you supply them via the environment?

The code

Assume you have code that changes behaviour based on feature flags. You want to test the old and the new features. Some features are internal improvements that do not change the API, so also the tests are the same. Still, you want to test it.

Here is a simple withFixture example. You can pull in the feature flags from the configMap construct of ScalaTest.

// src/test/scala/FeatureFlagSpec.scala
package org.bargsten.spielwiese.scala2

import org.scalatest.Outcome
import org.scalatest.flatspec.FixtureAnyFlatSpec
import org.scalatest.matchers.should.Matchers

class FeatureFlagSpec extends FixtureAnyFlatSpec with Matchers {
  case class FixtureParam(flags: Set[FeatureFlag])

  def withFixture(test: OneArgTest): Outcome = {
    val flags = test.configMap
      .map(_.split(raw"[|,]").map(s => FeatureFlag(s)))

  it should "contain A flag" in { f =>
    f.flags should contain(FeatureFlag("A"))

case class FeatureFlag(name: String)

with sbt

// build.sbt
val featureFlagsArg = sys.env
  .map(ff => s"-DfeatureFlags=$ff")
  .map(Tests.Argument(TestFrameworks.ScalaTest, _))
Test / testOptions ++= featureFlagsArg

call it with

FEATURE_FLAGS="A,B,C" sbt test

with maven

<!-- pom.xml -->
<!-- ... -->
<!-- ... -->

call it with

FEATURE_FLAGS="A\,B\,C" mvn test

(You need to escape the comma, because the maven plugin config option expects that the list of configMap entries is separated by comma.)

See also