Golang测试包概述
在这篇Golang文章中,我们将学习测试包的概述,使用两个测试函数以及使用迭代。
测试分为两种类型:手动测试和自动化测试,手动测试需要手动运行定义好的测试集,而自动化测试需要编写一个程序来测试软件。这里我们将使用两个测试函数和迭代方法来展示测试包的重要性。
算法
-
第一步 − 在程序中导入所需包。
-
第二步 − 创建一个测试函数,在该函数中调用要测试的函数。
-
第三步 − 使用测试用例检查和分析函数,使用 go test 命令查看错误,如果没有错误则返回 Pass。
示例1
在这个示例中,创建两个测试函数来了解要检查的函数中的错误。函数的结果将被记录在短变量中,然后与正确的输出进行比较。
package mypackage
import "testing"
func Test_function(t *testing.T) {
result := first_function()
if result != "Hello, alexa!" {
t.Errorf("期望得到 'Hello, alexa!' 但是得到了 '%s'", result)
}
}
func Test_another_function(t *testing.T) {
result := Another_function()
if result != 64 {
t.Errorf("期望得到 64 但是得到了 %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("期望得到 %f 但是得到了 %f", testCase.expected, result)
}
}
}
输出
Pass
结论
我们执行并总结了测试包的实现过程。在第一个示例中,我们创建了两个测试函数,并在每个测试函数中将函数的输出与准确输出进行了比较。在第二个示例中,我们创建了一个测试用例结构,并对其进行了迭代以检查错误。
极客教程