【Duke】单元测试 033 - PingPongGooo/GoFoundation GitHub Wiki

package testing

func square(op int) int  {
	return op*op
}
package testing

import "testing"

func TestSquare(t *testing.T)  {
	inputs := [...]int{1,2,3}   // 表格测试法
	expected := [...]int{1,4,9}

	for i := 0; i < len(inputs); i++ {
		ret:=square(inputs[i])
		if ret!=expected[i] {
			t.Errorf("input is %d, the expected is %d, the actual %d",inputs[i],expected[i],ret)
		}
	}
}

内置单元测试框架
Fail,Error:该测试失败,该测试继续(该测试剩下的代码还会执行),其他测试继续执行
FailNow,Fatal:该测试失败,该测试中止(该测试剩下的代码不会执行),其他测试继续执行
package testing

import (
	"fmt"
	"testing"
)

func TestSquare(t *testing.T)  {
	inputs := [...]int{1,2,3}
	expected := [...]int{1,4,9}

	for i := 0; i < len(inputs); i++ {
		ret:=square(inputs[i])
		if ret!=expected[i] {
			t.Errorf("input is %d, the expected is %d, the actual %d",inputs[i],expected[i],ret)
		}
	}
}

func TestErrorIncode(t *testing.T)  {
	fmt.Println("Start")
	t.Error("Error")
	fmt.Println("End")
}

func TestFatalIncode(t *testing.T)  {
	fmt.Println("Start")
	t.Fatal("Error")
	fmt.Println("End")
}

=== RUN   TestSquare
--- PASS: TestSquare (0.00s)
=== RUN   TestErrorIncode
Start
End
--- FAIL: TestErrorIncode (0.00s)
    functions_test.go:22: Error
=== RUN   TestFatalIncode
Start
--- FAIL: TestFatalIncode (0.00s)
    functions_test.go:28: Error
FAIL

内置单元测试框架

代码覆盖率
go test -v -cover

断言   下面的库,里边有很多预置的断言
https://github.com/stretchr/testify

go get -u github.com/stretchr/testify/assert

func TestSquare(t *testing.T)  {
	inputs := [...]int{1,2,3}
	expected := [...]int{1,4,9}

	for i := 0; i < len(inputs); i++ {
		ret:=square(inputs[i])

		assert.Equal(t,expected[i],ret) // github.com/stretchr/testify/assert 中的 预置的断言
	}
}