Go 编程实例【测试日志打印】

日志打印级别

A. Debug级别:用来调试程序,日志最详细。对程序性能影响比较大。
B. Trace级别:用来追踪问题。
C. Info级别:打印程序运行过程中比较重要的信息,比如访问日志。
D. Warn级别:警告日志,说明程序运行出现了潜在的问题。
E. Error级别:错误日志,程序运行发生错误,但不影响程序运行。
F. Fatal级别:严重错误日志,发生的错误会导致程序退出。

Go 总是会缓存程序构建的结果,以便在将来使用(可以加速构建速度)。

被缓存的构建结果保存在 go env GOCACHE 目录中,可以手动清除缓存结果,执行 go clean -cache即可。

运行 go clean -testcache 可以删除测试的缓存结果,但不会删除构建结果缓存。

t.Fail()

测试结果为失败,但其后的代码依然会被执行。

go 语言测试用例失败的触发必须手动调用 t.Fail/t.FailNow/t.Errorf/t.Fatalf 等方法才可以,并不像其它语言支持测试断言,由断言失败触发。

t.FailNow()

会令测试结果为失败,但其后的代码不再执行,不会影响其它测试用例的执行。

测试日志打印

/root/www/test/main_test.go

package main

import "testing"

func introduce() string {
    
    
	return "Welcome to my Golang column."
}

func TestIntroduce(t *testing.T) {
    
    
	intro := introduce()
	expected := "Welcome to my Golang column."
	if intro != expected {
    
    
		t.Errorf("The actual introduce %q is not the expected.", intro)
	}
	t.Logf("The expected introduce is %q.\n", expected)
}

可以使用 t.Logt.Logf 方法打印测试日志,这两个方法会在测试失败时,进行打印,在测试成功的时候,是不进行打印的。

如果想在测试结果中看到所有的日志,可以使用 -v 参数。

root@debiancc:~/www/test# go test -v
=== RUN   TestIntroduce
    main_test.go:15: The expected introduce is "Welcome to my Golang column.".
--- PASS: TestIntroduce (0.00s)
PASS
ok      grpc-helloworld 0.001s
root@debiancc:~/www/test#

猜你喜欢

转载自blog.csdn.net/weiguang102/article/details/130473101
今日推荐