
Golang 单元测试资源和教程
单元测试对于确保代码的健壮性和正确性至关重要。本文将介绍几种资源和教程,帮助您学习和实施 Golang 单元测试。
资源
官方文档:
- [Testing in Go](https://go.dev/testing/)
书籍:
- [Go Testing 2nd Edition](https://www.manning.com/books/go-testing-2nd-edition)
- [The Go Programming Language](https://go.dev/book/testing/)
在线课程:
立即学习“go语言免费学习笔记(深入)”;
- [Golang Unit Testing](https://www.udemy.com/course/go-lang-unit-testing/)
- [Go Testing Foundations](https://www.coursera.org/learn/go-testing-foundations)
教程
设置单元测试:
import (
"testing"
)
func TestAdd(t *testing.T) {
// ...
}编写断言:
if output != expected {
t.Errorf("Expected %v, got %v", expected, output)
}覆盖率:
func TestSomething(t *testing.T) {
if coverage.Cmd == nil {
t.Skip("coverage not enabled")
}
defer coverage.Stop()
// ...
}实战案例:
一个简单的添加函数:
func Add(a, b int) int {
return a + b
}单元测试:
func TestAdd(t *testing.T) {
tests := []struct {
input []int
expected int
}{
{[]int{1, 2}, 3},
{[]int{-10, 10}, 0},
{[]int{0, 0}, 0},
}
for _, test := range tests {
output := Add(test.input[0], test.input[1])
if output != test.expected {
t.Errorf("Expected %v, got %v", test.expected, output)
}
}
}










