Scala set a config value for a particular test

Viewed 777

I have a reference.conf file which specifies a config value as

prop {
    type = 2
}

I have scala test class and have a number of the test under it. I want this config value to remain the same for all tests except for one test which requires it to be 3. What is the best way to load a different config value for one particular test? Right now the config values are automatically loaded because I extend ScalatestRouteTest.

So how can I make a config file (or string) especially for that test and load it by specifying it while loading a config

1 Answers

If you have control over Config object (because maybe it is passed as a parameter), you can just override some value in config:

val config = ConfigFactory.load.withValue(
    "prop.type",
    ConfigValueFactory.fromAnyRef(5)
).resolve()

Calling resolve is necessary if any other properties depend on prop.type, for example:

prop.type2 = ${prop.type} + 1

You can also use system properties since they are mapped directly to values from the config.

This means you can do something like this at the start of the test:

System.setProperty("prop.type", 5.toString)
ConfigFactory.invalidateCaches()

Of course, since changing system properties programmatically is not thread-safe, so it's not suitable for production code, but only for tests.

Related