简体   繁体   中英

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?

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 - ie 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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM