I'm trying to do a test:
- The test cases are stored in a
slice
ofstruct
s withinput
andexpect
. - The expect can be
int
orError
.
The goal is to expect an Error if the input will cause an invalid result. I've learnt that it's not recommended to return an error string in Go. How can I expect an error whilst doing unit testing in Go?
Here's the code:
func TestArrIdx(t *testing.T) {
arr := [5]int{1, 2, 3, 4, 5}
tests := []struct {
input int
expect int // or an error
}{
{len(arr) - 1, 5},
{1, 2},
// {-1, t.Error},
}
for _, test := range tests {
testName := fmt.Sprintf("%d", test.input)
t.Run(testName, func(t *testing.T) {
got := arr[test.input]
if got != test.expect {
t.Errorf("got %v, want %v", got, test.expect)
} else {
fmt.Printf("got %v expect %v\n", got, test.expect)
}
})
}
}
Aucun commentaire:
Enregistrer un commentaire