golang 自动化测试

文章目录

    为了提升开发效率,很多时候我只想在终端下敲代码,并执行自动化测试验证。相比,每改一点代码,就打开浏览器手动测试,要节省很多时间,也不容易临时起意去论坛闲逛了。。。

    依赖包

    import "testing"
    

    测试代码规范

    • 文件名格式:file_test.go
    • 功能测试函数名格式:TestFuction
    • 性能测试函数名格式:BenchmarkFunction,执行命令 go test -bench 时会运行

    assert 库

    https://github.com/stretchr/testify

    内置的 Errorf 写法太啰嗦了,找了一个支持 assert 语法的库。我看 golang gin 框架中就是用的这个库。

    示例代码:

    request_test.go

    package utils
    
    import (
    	"github.com/stretchr/testify/assert"
    	"testing"
    )
    
    func TestIsMobile(t *testing.T) {
    	pcAgent := "HTTP USER AGENT: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36"
    	mobileAgent := "HTTP USER AGENT: Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1"
    	assert.Equal(t, IsMobile(pcAgent), false)
    	assert.Equal(t, IsMobile(mobileAgent), true)
    }
    

    go test -v 与 go test 输出信息上有什么区别

    > go test -v
    === RUN   TestIsMobile
    --- PASS: TestIsMobile (0.00s)
    PASS
    ok      sunzhongwei.com/go_tool/utils   0.027s
    
    > go test
    PASS
    ok      sunzhongwei.com/go_tool/utils   0.027s
    

    测试案例不通过会提示什么

    > go test
    --- FAIL: TestIsMobile (0.00s)
        request_test.go:12:
                    Error Trace:    request_test.go:12
                    Error:          Not equal:
                                    expected: false
                                    actual  : true
                    Test:           TestIsMobile
    FAIL
    exit status 1
    FAIL    sunzhongwei.com/go_tool/utils   0.027s
    

    更多

    参考

    https://golang.org/pkg/testing/

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式