Your shop runs in two places with the same code: on your computer while you build it, the development environment, and on the server where customers use it, production. Only a few settings differ. The server tells the program where it runs with an environment variable, a named text value that Java gives you as a map: System.getenv(), a Map<String, String>.
You read one with getOrDefault: the name, then a default for when it isn't set. If a method takes the environment as a parameter instead of calling System.getenv() itself, a test can hand in a map of its own, and the real environment is never touched. Here a shop picks its currency:
static String currency(Map<String, String> env) {
return env.getOrDefault("SHOP_CURRENCY", "USD");
}
currency(System.getenv()); // the real environment
currency(Map.of("SHOP_CURRENCY", "EUR")); // "EUR", in a test
The setting that matters most is debug mode, "DEBUG" in the shop's config map. When a request crashes, debug mode shows the full error and where in your code it happened: handy on your computer, a gift to attackers on the server. So it must be on only when SHOP_ENV is exactly development, and off for production, for a missing variable and for a typo.
The check starts your shop with SHOP_ENV=development, calls your method in each case, and runs your test on the shop and on a copy that keeps debug mode on everywhere. It must print:
Your shop, started on your computer with SHOP_ENV=development:
DEBUG = true
loadConfig on your computer, with SHOP_ENV=development:
DEBUG = true
loadConfig on the server, with SHOP_ENV=production:
DEBUG = false
loadConfig on a server where nobody set SHOP_ENV:
DEBUG = false
loadConfig with SHOP_ENV=Development, a typo:
DEBUG = false
Your tests on the shop:
testDebugOffInProduction ... ok
1 test: OK
Your tests on a copy that keeps debug mode on everywhere:
testDebugOffInProduction ... FAIL
AssertionError: expected: <false> but was: <true>
1 test: 1 failed, so they caught this bug
Your task: write loadConfig(config, env), which reads SHOP_ENV from env with the default "production" and puts "DEBUG" into config, and call it in run() for the shop's config with the real environment. Then write ConfigTests with testDebugOffInProduction, which loads the settings into a new map with SHOP_ENV set to production and checks that debug mode is off.
Assignment
Follow the Coding Tutorial to load the shop's settings from SHOP_ENV and write the test that keeps debug mode off in production.
Hint
A comparison with equals is already true or false, so you can put it straight into the map. In the test, use a new HashMap instead of the shop's config, hand in Map.of("SHOP_ENV", "production") as the environment, and check the setting with assertFalse.
Free plan: 30 tutor messages. PRO is unlimited.
