Skip to main content
Version: 2.x

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:

  1. a complete map loads into the expected value,
  2. a missing key falls back to the default,
  3. 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.envProvider in unit tests. A test that depends on the developer's environment is not repeatable.
  • Code that reads its settings with ZIO.config takes the provider from the runtime. In a test, run it inside ZIO.withConfigProvider(ConfigProvider.fromMap(...)), or provide Runtime.setConfigProvider(...) as a layer, to swap in a map. See ZIO core providers.
  • For a test that reads a real HOCON file, use ConfigProvider.fromHoconString with the file's content as a string.

See Config providers for the providers you can build from a map or a string, and Errors for the error values to match on.

ZIO Chat

Hi, fellow coder! ๐ŸŒŸ Welcome to your ZIO adventure with the ZIO Chat Bot. ๐Ÿš€ Let's master functional Scala together. From referential transparency to concurrent prowess, I've got your back. Ready to dive in? Your questions, my insights โ€“ let's conquer ZIO! ๐Ÿ’ก๐Ÿค–