Test Configuration Setup⚓︎
Almost everyone one of us, working on thousands of lines of codebases with tons of features and feature flags. At GOJEK Some of them might be controlled by ENV variable or an introduced parameter. In this article, I'll show a clean way to set up a specific configuration for a particular test case.
We have a typical config like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|
In the service test file, we want to enable this feature. Previously what we used to do in such scenarios is setup env variable and load the config and set the initial value again in the defer and Load the config like below.
Refactor Refactor Refactor⚓︎
As you see, this is a repetitive code block for each test case that needs to handle env variables. What we can do here is to extract this out as method and pull up the member to config class and use that everywhere we need like below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
Bug
Missing this additional ()
at the end of line number 9 in service_test.go
file would cause a silly bug. Why? This might make your test flaky as
well.
1 |
|
Not having the extra ()
at the end will not call the function returned by
TestPrepareConfig, thus whatever the config we set is not reverted.
Whoever will work on this code base, does not have to understand how configuration has set up in the test; instead, it is abstracted away and allows the developer to focus only on the test subject. By taking advantage of defer in Golang, we reset the initial config value at the end of the test, thus keeping the original config intact outside the test scope.
Happy Coding