Joey Baruch
Joey Baruch

Reputation: 5229

Typesafe Config: Overriding values for unit testing purposes

In a unit test of a class that requires a config: Config, I'd like to declare visually (not in a config file located in another place) the assumed configurations settings for the test.

So for example, I'd like to do something like this:

class myClassSpec extends AnyFlatSpec{
  val myTestingConfigForThisTestCase = 3L
  val config = ConfigFactory.load()
                .withValue("my-config-path", myTestingConfigForThisTestCase)
  ...
}

However, withValue expects a ConfigValue and there seem to be no implicit conversions between basic types and that.

Any ideas on a simple solution?

Upvotes: 4

Views: 3479

Answers (1)

J0HN
J0HN

Reputation: 26931

You might want to use ConfigValueFactory - most likely something like

ConfigFactory.load()
  .withValue(
    "my-config-path", 
    ConfigValueFactory.fromAnyRef(myTestingConfigForThisTestCase)
  )

This doesn't scale well though - i.e. if you need overriding more than 2-3 settings it gets more boilerplaty than ConfigFactory.parseString + withFallback:

val configOverride = """
{
   my-config-path: $myTestingConfigForThisTestCase
   other-config {
      ...
   }
}
"""
val config = ConfigFactory.parseString(configOverride)
   .withFallback(ConfigFactory.load())

Upvotes: 6

Related Questions