Go单元测试代码示例

31 阅读1分钟
package main
​
func Add(a int, b int) int{
    return a + b
}
func Mul(a int, b int) int{
    return a * b
}
package main
​
import (
    "testing"
    "github.com/stretchr/testify/assert"
)
​
func Test_Add(t *testing.T){
    t.Run("add-case1", func(t *testing.T){
        c := Add(1, 2)
        assert.Equal(t, 3, c)
    })
    t.Run("add-case2", func(t *testing.T){
        c := Add(4, 5)
        assert.Equal(t, 9, c)
    })
}
func Test_Mul(t *testing.T){
    t.Run("mul-case1", func(t *testing.T){
        c := Mul(1, 2)
        assert.Equal(t, 2, c)
    })
    t.Run("mul-case2", func(t *testing.T){
        c := Mul(4, 5)
        assert.Equal(t, 20, c)
    })
}
root@ubuntu22:~/lab# go test -v
=== RUN   Test_Add
=== RUN   Test_Add/add-case1
=== RUN   Test_Add/add-case2
--- PASS: Test_Add (0.00s)
    --- PASS: Test_Add/add-case1 (0.00s)
    --- PASS: Test_Add/add-case2 (0.00s)
=== RUN   Test_Mul
=== RUN   Test_Mul/mul-case1
=== RUN   Test_Mul/mul-case2
--- PASS: Test_Mul (0.00s)
    --- PASS: Test_Mul/mul-case1 (0.00s)
    --- PASS: Test_Mul/mul-case2 (0.00s)
PASS
ok      lab     0.038s
​
root@ubuntu22:~/lab# go test Test_Add -v
package Test_Add is not in std (/usr/local/go/src/Test_Add)
​
root@ubuntu22:~/lab# go test -run Test_Add -v
=== RUN   Test_Add
=== RUN   Test_Add/add-case1
=== RUN   Test_Add/add-case2
--- PASS: Test_Add (0.00s)
    --- PASS: Test_Add/add-case1 (0.00s)
    --- PASS: Test_Add/add-case2 (0.00s)
PASS
ok      lab     0.002s
​
root@ubuntu22:~/lab# go test -run Test_Add/add-case1 -v
=== RUN   Test_Add
=== RUN   Test_Add/add-case1
--- PASS: Test_Add (0.00s)
    --- PASS: Test_Add/add-case1 (0.00s)
PASS
ok      lab     0.003s