Golang:Testing

From musings of k8
Jump to: navigation, search

Golang Testing

This method works best when the testCase is a large struct, and only tiny changes are made to that struct for each case.

func Func(value int) {
  return value > 0
}

func TestFunc(t *testing.T) {
  type testCase struct {
    desc  string
    ok    bool
    value int
  }

  okFunc := func(changeFn func(*testCase)) testCase {
    tc := &testCase {
      ok: true,
    }
    if changeFn != nil {
      changeFn(tc)
    }
    return *tc
  }

  for _, tc := range []testCase {
    // ok values.
    okFunc(nil),
    okFunc(func(tc *testCase) {
      tc.desc = "one"
      tc.value = 1
    },
    // not-ok values.
    testCase{"not-ok"},
  }{
    if got, want := Func(tc.value), tc.ok; got != want {
      t.Errorf("%s: Func(%d) = %t", tc.desc, tc.value, got)
    }  
  }
}