Golang 测试包的概述
在这篇golang文章中,我们将学习测试包的概述,使用两个测试函数和迭代。
测试分为两种类型:手动测试和自动化测试。手动测试是手动完成一组定义好的测试用例,而自动化测试是通过编写代码创建程序来测试软件。在这里,我们将使用两个测试函数和迭代方法来展示测试包的重要性。
步骤
- 步骤1 - 导入程序中所需的包
-
步骤2 - 创建一个测试函数,在该函数中调用要测试的函数
-
步骤3 - 使用测试用例检查和分析函数,使用go test命令查看错误信息,如果没有错误则返回通过
示例1
在这个示例中,创建了两个测试函数来确定要检查的函数中的错误。函数的结果将被记录在short变量中,然后与正确的输出进行匹配。
package mypackage
import "testing"
func Test_function(t *testing.T) {
result := first_function()
if result != "Hello, alexa!" {
t.Errorf("Expected 'Hello, alexa!' but got '%s'", result)
}
}
func Test_another_function(t *testing.T) {
result := Another_function()
if result != 64 {
t.Errorf("Expected 64 but got %d", result)
}
}
输出
Pass
示例2
在这个示例中,将创建一个测试函数,并创建一些测试用例。然后,将迭代并测试所调用的函数上的测试用例。
package mypackage
import (
"math"
"testing"
)
func Test_calculate_squareRoot(t *testing.T) {
test_cases := []struct {
input float64
expected float64
}{
{4, 2},
{9, 3},
{16, 4},
{25, 5},
{36, 6},
}
for _, testCase := range test_cases {
result := CalculateSquareRoot(testCase.input)
if math.Abs(result-testCase.expected) > 0.001 {
t.Errorf("Expected %f but got %f", testCase.expected, result)
}
}
}
输出
Pass
结论
我们执行并完成了测试包实现过程的程序。在第一个示例中,我们创建了两个测试函数,并在每个测试函数中检查了函数的输出与实际输出是否相符。在第二个示例中,我们创建了一个测试用例结构并对其进行迭代,以检查错误。