Difference between revisions of "Golang:Testing"

From musings of k8
Jump to navigation Jump to search
(Created page with "# Golang Testing")
 
 
Line 1: Line 1:
 
# Golang Testing
 
# 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.
 +
 +
```go
 +
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)
 +
    } 
 +
  }
 +
}
 +
```

Latest revision as of 14:39, 20 March 2020

  1. 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.

```go 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)
   }  
 }

} ```