面试题答案
一键面试1. 编写被测试函数
首先编写 add
函数,通常放在一个 .go
文件中,比如 math.go
:
package main
func add(a, b int) int {
return a + b
}
2. 编写测试函数
在同一个包下创建一个 *_test.go
文件,比如 math_test.go
。在这个文件中编写测试函数,使用 testing
标准库。
package main
import (
"testing"
)
func TestAdd(t *testing.T) {
result := add(2, 3)
if result != 5 {
t.Errorf("add(2, 3) = %d; want 5", result)
}
}
3. 测试函数命名规则
测试函数的命名必须以 Test
开头,后面紧跟被测试函数的名称,一般格式为 Test<FunctionName>
。例如,测试 add
函数,测试函数名为 TestAdd
。这种命名规则是 testing
标准库识别测试函数的依据。
4. 常用断言方法
t.Errorf
和t.Fatalf
:t.Errorf
用于报告测试失败,但测试会继续执行后续代码。格式为t.Errorf(format string, args ...interface{})
,如上述例子中使用t.Errorf("add(2, 3) = %d; want 5", result)
报告实际结果与期望结果不符。t.Fatalf
同样用于报告测试失败,但它会立即终止当前测试函数的执行。格式为t.Fatalf(format string, args ...interface{})
。例如,如果在某个重要检查点失败,后续步骤无意义时可使用t.Fatalf
。
require
包(非标准库,但常用):require
包提供了更简洁的断言方式。例如在github.com/stretchr/testify/require
包中:
package main
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestAddWithRequire(t *testing.T) {
result := add(2, 3)
require.Equal(t, 5, result, "add(2, 3) should be 5")
}
- `require.Equal` 断言两个值是否相等,若不相等则终止测试并输出错误信息。第一个参数为 `*testing.T`,第二个参数为期望的值,第三个参数为实际值,第四个参数(可选)为错误信息。
通过以上步骤,就可以运用 testing
标准库为 add
函数编写单元测试,并了解相关的命名规则和常用断言方法。