go 语言 测试日志打印

缓存目录

Go 总是会缓存程序构建的结果,以便在将来使用(可以加速构建速度)。当有任何变动时,缓存就会失效,构建过程会真正的被执行。被缓存的构建结果保存在go env GOCACHE目录中,为了防止目录中的数据越来越多,go会自动删除不经常使用的缓存文件。可以手动清除缓存结果,执行go clean -cache即可。

go test命令也会把测试成功的结果缓存起来,如果测试代码和源代码没有改动,再次运行测试时,直接使用缓存的结果。当源码和测试代码有改动时,缓存结果就会失效,测试会被真正的运行。运行go clean -testcache可以删除测试的缓存结果,但不会删除构建结果缓存

测试日志打印

可以使用t.Logt.Logf方法打印测试日志,这两个方法会在测试失败时,进行打印,在测试成功的时候,是不进行打印的。如果想在测试结果中看到所有的日志,可以使用-v参数

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.Logf()中的内容
--- FAIL: TestIntroduce (0.00s)
    demo53_test.go:41: The actual introduce "Welcome to my Golang column." is not the expected.
    demo53_test.go:44: The expected introduce is "Welcome to my golang column.".
FAIL
FAIL	puzzlers/article20/q2	0.013s
FAIL

t.Fail()t.FailNow()

t.Fail()令测试结果为失败,但其后的代码依然会被执行。go 语言测试用例失败的触发必须手动调用t.Fail/t.FailNow/t.Errorf/t.Fatalf等方法才可以,并不像其它语言支持测试断言,由断言失败触发。

func TestFail(t *testing.T) {
	t.Fail()
	t.Log("Failed.") // 可以被执行到
}

t.FailNow()也会令测试结果为失败,但其后的代码不再执行,不会影响其它测试用例的执行

func TestFail(t *testing.T) {
	t.FailNow()
	t.Log("Failed") // 不能被执行到
}

t.Errorf()t.Error()

打印日志并使测试失败,等效于调用t.Logf/t.Log后,又调用了t.Fail

// t.Error 等效于在调用 t.Log 后,接着又调用了 t.Fail
// Error is equivalent to Log followed by Fail.
func (c *common) Error(args ...interface{}) {
	c.log(fmt.Sprintln(args...))
	c.Fail()
}

// Errorf is equivalent to Logf followed by Fail.
func (c *common) Errorf(format string, args ...interface{}) {
	c.log(fmt.Sprintf(format, args...))
	c.Fail()
}

t.Fatalt.Fatalf方法

打印日志并使测试失败,在其后的代码不会被执行,当前测试用例立即结束,但不会影响其它测试用例,等效于调用t.Logf/t.Log后,又调用了t.FailNow

// Fatal is equivalent to Log followed by FailNow.
func (c *common) Fatal(args ...interface{}) {
	c.log(fmt.Sprintln(args...))
	c.FailNow()
}

// Fatalf is equivalent to Logf followed by FailNow.
func (c *common) Fatalf(format string, args ...interface{}) {
	c.log(fmt.Sprintf(format, args...))
	c.FailNow()
}