Last active
December 6, 2021 09:06
-
-
Save denisvmedia/f4405faf77440e726028d267d05a25d5 to your computer and use it in GitHub Desktop.
Go unit test example: _test package suffix + multiple test cases
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package math | |
import "errors" | |
var ErrCantDivideByZero = errors.New("can't divide by zero") | |
// divide cannot be tested directly | |
func divide(x, y float32) float32 { | |
return x / y | |
} | |
// Divide is exported and will be tested | |
func Divide(x, y int) (int, error) { | |
if y == 0 { | |
return 0, ErrCantDivideByZero | |
} | |
return int(divide(float32(x), float32(y))), nil | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package math_test // _test suffix is used to prevent private members direct tests | |
import ( | |
"log" | |
"os" | |
"testing" | |
. "mynamespace/math" // dot import to use public symbols without a package name | |
) | |
func TestDivide(t *testing.T) { | |
cases := []struct { | |
name string | |
x int | |
y int | |
res int | |
err error | |
}{ | |
{ | |
name: "integer dividable without reminder", | |
x: 4, | |
y: 2, | |
res: 2, | |
}, | |
{ | |
name: "integer dividable with reminder", | |
x: 3, | |
y: 2, | |
res: 1, | |
}, | |
{ | |
name: "divide by zero", | |
x: 4, | |
y: 0, | |
err: ErrCantDivideByZero, | |
}, | |
{ | |
name: "Intentionally broken test case", | |
x: 0, | |
y: 0, | |
res: 1, | |
err: nil, | |
}, | |
} | |
for _, tc := range cases { | |
t.Run(tc.name, func(t *testing.T) { | |
log.Print("before test") | |
defer log.Print("after test") | |
res, err := Divide(tc.x, tc.y) | |
if err != tc.err { | |
t.Errorf("error expected %v, got %v", tc.err, err) | |
} | |
if res != tc.res { | |
t.Errorf("result expected %d, got %d", tc.res, res) | |
} | |
}) | |
} | |
} | |
// inits tests globally (package wide) | |
func TestMain(m *testing.M) { | |
log.Print("setup all") | |
code := m.Run() | |
log.Print("teardown all") | |
os.Exit(code) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: