title: How to test the passing of arguments in Golang?
body: <pre><code>package main
  
  import (
      "flag"
      "fmt"
  )
  
  func main() {
      passArguments()
  }
  
  func passArguments() string {
      username := flag.String("user", "root", "Username for this server")
      flag.Parse()
      fmt.Printf("Your username is %q.", *username)
  
      usernameToString := *username
      return usernameToString
  }
  </code></pre>
  
  <p>Passing an argument to the compiled code:</p>
  
  <p><code>./args -user=bla</code></p>
  
  <p>results in:</p>
  
  <p><code>Your username is "bla"</code></p>
  
  <p>the username that has been passed is displayed. </p>
  
  <hr>
  
  <p><strong>Aim:</strong> in order to prevent that the code needs to be build and run manually every time to test the code the aim is to write a test that is able to test the passing of arguments.</p>
  
  <hr>
  
  <p><strong>Attempt</strong></p>
  
  <p>Running the following test:</p>
  
  <pre><code>package main
  
  import (
      "os"
      "testing"
  )
  
  func TestArgs(t *testing.T) {
      expected := "bla"
      os.Args = []string{"-user=bla"}
  
      actual := passArguments()
  
      if actual != expected {
          t.Errorf("Test failed, expected: '%s', got:  '%s'", expected, actual)
      }
  }
  </code></pre>
  
  <p>results in:</p>
  
  <pre><code>Your username is "root".Your username is "root".--- FAIL: TestArgs (0.00s)
      args_test.go:15: Test failed, expected: 'bla', got:  'root'
  FAIL
  coverage: 87.5% of statements
  FAIL    tool    0.008s
  </code></pre>
  
  <p><strong>Problem</strong></p>
  
  <p>It looks like that the <code>os.Args = []string{"-user=bla</code> is not able to pass this argument to the function as the outcome is <code>root</code> instead of <code>bla</code></p>