-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_test.go
74 lines (61 loc) · 1.99 KB
/
main_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"testing"
)
// Tests have to start with prefix Test to get recognized by
// the go test tool. We also need a parameter of type *testing.T
// which offers testing functions. The typical order of instructions
// is test setup (data preparation), followed by a function call for
// the functionality to test, followed by a verification step.
func TestProduct(t *testing.T) {
// Check very basic product.
result := product(1, 2, 3)
checkEqual(t, result, 6)
// Check no factor corner case.
result = product()
checkEqual(t, result, 0)
// Check with negative numbers.
result = product(-7, 3, 10, 2)
checkEqual(t, result, -420)
// Check with one zero element.
result = product(-3, 5, 20, 0)
checkEqual(t, result, 0)
}
// Error methods are helpful for failing a test but continuing the test
// function.
func checkEqual(t *testing.T, actual, expected int) {
t.Helper()
if actual != expected {
t.Errorf("Expected %v but got %v", expected, actual)
}
}
func TestRemove(t *testing.T) {
slice := []int{4, 2, -3, 8, 0}
// Remove last element.
slice = remove(slice, 0)
expected := []int{4, 2, -3, 8}
checkEqualSlices(t, slice, expected)
// Remove first element.
slice = remove(slice, 4)
expected = []int{2, -3, 8}
checkEqualSlices(t, slice, expected)
// Remove middle element.
slice = remove(slice, -3)
expected = []int{2, 8}
checkEqualSlices(t, slice, expected)
}
// Fatal methods are helpful for failing a test when it makes no sense
// to continue the test function due to results that maybe built on each
// other. For simplicity we can also use reflect.DeepEqual to compare
// slices. But there is no builtin equality check for slices in golang.
func checkEqualSlices(t *testing.T, actual, expected []int) {
t.Helper()
if len(actual) != len(expected) {
t.Fatalf("Expected slice %v but got %v", expected, actual)
}
for index := 0; index < len(actual); index++ {
if actual[index] != expected[index] {
t.Fatalf("Expected slice %v but got %v", expected, actual)
}
}
}