How to Test Config
A config description is a value, so tests can load it from a map instead of the real environment. This guide shows how to write tests that check the settings a program reads and how it reports bad values.
Goalโ
Check, without touching the machine's environment or files, that:
- a complete map loads into the expected value,
- a missing key falls back to the default,
- a wrong value fails with a
Config.Error.
Step 1: Use a Map as the Sourceโ
ConfigProvider.fromMap reads a Map[String, String]. It is the same type a real provider produces, so the code under test does not change:
import zio._
import zio.config._
import zio.config.magnolia.deriveConfig
final case class Service(host: String, port: Int, timeoutSeconds: Int)
val serviceDescription: Config[Service] =
(Config.string("HOST") zip Config.int("PORT") zip Config.int("TIMEOUT").withDefault(30)).to[Service]
Step 2: Check the Happy Pathโ
Load a complete map and compare the result with the expected value:
val complete: ConfigProvider =
ConfigProvider.fromMap(Map("HOST" -> "localhost", "PORT" -> "8080", "TIMEOUT" -> "5"))
val loadedComplete: IO[Config.Error, Service] = complete.load(serviceDescription)
// Expected: Service("localhost", 8080, 5)
Step 3: Check the Defaultโ
Leave TIMEOUT out, and the description falls back to its default:
val withoutTimeout: ConfigProvider =
ConfigProvider.fromMap(Map("HOST" -> "localhost", "PORT" -> "8080"))
val loadedDefault: IO[Config.Error, Service] = withoutTimeout.load(serviceDescription)
// Expected: Service("localhost", 8080, 30)
Step 4: Check the Failureโ
Give PORT a value that is not a number, and the load fails:
val badPort: ConfigProvider =
ConfigProvider.fromMap(Map("HOST" -> "localhost", "PORT" -> "not-a-number"))
val failed: IO[Config.Error, Service] = badPort.load(serviceDescription)
// Expected: a Config.Error that names PORT
In a ZIO Test spec, use assertZIO(provider.load(desc))(...) or .exit with an assertTrue on the result.
Notesโ
- Do not use
ConfigProvider.envProviderin unit tests. A test that depends on the developer's environment is not repeatable. - Code that reads its settings with
ZIO.configtakes the provider from the runtime. In a test, run it insideZIO.withConfigProvider(ConfigProvider.fromMap(...)), or provideRuntime.setConfigProvider(...)as a layer, to swap in a map. See ZIO core providers. - For a test that reads a real HOCON file, use
ConfigProvider.fromHoconStringwith the file's content as a string.
Relatedโ
See Config providers for the providers you can build from a map or a string, and Errors for the error values to match on.