Test your code!
func TestXxx(*testing.T)
❯ tree go-unit-test
go-unit-test
├── go.mod
└── math
├── math.go
└── math_test.go
1 directory, 3 files
package math
func Add(x, y int) int {
return x + y
}
func Subtract(x, y int) int {
return x - y
}
func Divide(x, y int) float64 {
return float64(x / y)
}
func Multiply(x, y int) int {
return x * y
}
package math
import "testing"
func TestAdd(t *testing.T) {
result := Add(1, 3)
if result != 4 {
t.Errorf("Add(1, 3) FAILED. Expected %d, got %d\n", 4, result)
} else {
t.Logf("Add(1, 3) PASSED. Expected %d, got %d\n", 4, result)
}
}
❯ go test
PASS
ok go-unit-test/math 0.001s
❯ go test -v
=== RUN TestAdd
math_test.go:11: Add(1, 3) PASSED. Expected 4, got 4
--- PASS: TestAdd (0.00s)
PASS
ok go-unit-test/math 0.001s
❯ go test --cover
PASS
coverage: 25.0% of statements
ok go-unit-test/math 0.001s
func TestDivide(t *testing.T) {
result := Divide(1, 2)
if result != 0.5 {
t.Errorf("Divide(1, 2) FAILED. Expected %f, got %f\n", 0.5, result)
} else {
t.Logf("Divide(1, 2) PASSED. Expected %f, got %f\n", 0.5, result)
}
}
❯ go test -v
=== RUN TestAdd
math_test.go:11: Add(1, 3) PASSED. Expected 4, got 4
--- PASS: TestAdd (0.00s)
=== RUN TestDivide
math_test.go:19: Divide(1, 2) FAILED. Expected 0.500000, got 0.000000
--- FAIL: TestDivide (0.00s)
FAIL
exit status 1
FAIL go-unit-test/math 0.001s
❯ go get github.com/stretchr/testify/assert
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestSub(t *testing.T) {
// Arrange
var a int = 13
var b int = 9
var expected int = 4
// Act
var actual int = Subtract(a, b)
// Assert
assert.EqualValues(t, expected, actual, "Expected %d, got %f\n", expected, actual)
}
❯ go test -v --cover
=== RUN TestAdd
math_test.go:15: Add(1, 3) PASSED. Expected 4, got 4
--- PASS: TestAdd (0.00s)
=== RUN TestDivide
math_test.go:23: Divide(1, 2) FAILED. Expected 0.500000, got 0.000000
--- FAIL: TestDivide (0.00s)
=== RUN TestSub
--- PASS: TestSub (0.00s)
FAIL
coverage: 75.0% of statements
exit status 1
FAIL go-unit-test/math 0.002s
var _ = Describe("Books", func() { var book *books.Book BeforeEach(func() { book = &books.Book{ Title: "Les Miserables", Author: "Victor Hugo", Pages: 2783, } Expect(book.IsValid()).To(BeTrue()) }) It("can extract the author's last name", func() { Expect(book.AuthorLastName()).To(Equal("Hugo")) }) })