golang 自动化测试

发布时间: 2020-04-01 11:01:52 作者: 大象笔记

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

依赖包

import "testing"

测试代码规范

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/

我是一名山东烟台的开发者,联系作者