<p>When you want to set an environment variable in a Go test, you can use the <a href="https://golang.org/pkg/os/#Setenv"><code>os.Setenv</code></a> function. If you have multiple tests, you want to ensure the environment variable is unset after the test. This can be done with a <a href="https://blog.golang.org/defer-panic-and-recover"><code>defer</code></a> call to the <a href="https://golang.org/pkg/os/#Unsetenv"><code>os.Unsetenv</code></a> function:</p> <div class="highlight"><pre><span></span><span class="kn">package</span> <span class="nx">main_test</span> <span class="kn">import</span> <span class="p">(</span> <span class="s">&quot;testing&quot;</span> <span class="s">&quot;github.com/stretchr/testify/assert&quot;</span> <span class="p">)</span> <span class="kd">func</span> <span class="nx">Test_UsingEnvvar</span><span class="p">(</span><span class="nx">t</span> <span class="o">*</span><span class="nx">testing</span><span class="p">.</span><span class="nx">T</span><span class="p">)</span> <span class="p">{</span> <span class="nx">os</span><span class="p">.</span><span class="nx">Setenv</span><span class="p">(</span><span class="s">&quot;ENV_VAR&quot;</span><span class="p">,</span> <span class="s">&quot;value&quot;</span><span class="p">)</span> <span class="k">defer</span> <span class="nx">os</span><span class="p">.</span><span class="nx">Unsetenv</span><span class="p">(</span><span class="s">&quot;ENV_VAR&quot;</span><span class="p">)</span> <span class="nx">actual</span> <span class="o">:=</span> <span class="nx">os</span><span class="p">.</span><span class="nx">Getenv</span><span class="p">(</span><span class="s">&quot;ENV_VAR&quot;</span><span class="p">)</span> <span class="nx">assert</span><span class="p">.</span><span class="nx">Equals</span><span class="p">(</span><span class="nx">t</span><span class="p">,</span> <span class="s">&quot;value&quot;</span><span class="p">,</span> <span class="nx">actual</span><span class="p">)</span> <span class="p">}</span> </pre></div>

Related Posts

  • Assert vs require in testify
  • Handling Unix timestamps in JSON
  • Parsing a key pair from a PEM file in Go
  • Pointer vs value receivers
  • Testing exceptions in pytest