您如何使用“测试"在 Go 测试中打印?包裹? [英] How do you print in a Go test using the "testing" package?

查看:30
本文介绍了您如何使用“测试"在 Go 测试中打印?包裹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Go 中运行一个测试,并带有一条语句来打印一些东西(即用于调试测试),但它没有打印任何东西.

I'm running a test in Go with a statement to print something (i.e. for debugging of tests) but it's not printing anything.

func TestPrintSomething(t *testing.T) {
    fmt.Println("Say hi")
}

当我对这个文件运行 go test 时,这是输出:

When I run go test on this file, this is the output:

ok      command-line-arguments  0.004s

据我所知,真正让它打印的唯一方法是通过 t.Error() 打印它,如下所示:

The only way to really get it to print, as far as I know, is to print it via t.Error(), like so:

func TestPrintSomethingAgain(t *testing.T) {
    t.Error("Say hi")
}

输出这个:

Say hi
--- FAIL: TestPrintSomethingAgain (0.00 seconds)
    foo_test.go:35: Say hi
FAIL
FAIL    command-line-arguments  0.003s
gom:  exit status 1

我用谷歌搜索并浏览了手册,但没有找到任何东西.

I've Googled and looked through the manual but didn't find anything.

推荐答案

结构 testing.Ttesting.B两者都有 .Log.Logf 听起来正是您正在寻找的方法..Log.Logf 类似于 fmt.Printfmt.Printf 分别.

The structs testing.T and testing.B both have a .Log and .Logf method that sound to be what you are looking for. .Log and .Logf are similar to fmt.Print and fmt.Printf respectively.

在此处查看更多详细信息:http://golang.org/pkg/testing/#pkg-索引

See more details here: http://golang.org/pkg/testing/#pkg-index

fmt.X 打印语句 do 在测试中工作,但您会发现它们的输出可能不在您希望找到的屏幕上,因此,为什么您应该使用 testing 中的日志记录方法.

fmt.X print statements do work inside tests, but you will find their output is probably not on screen where you expect to find it and, hence, why you should use the logging methods in testing.

如果在您的情况下,您想查看未失败测试的日志,则必须提供 go test -v 标志(v 表示冗长).可以在此处找到有关测试标志的更多详细信息:https://golang.org/cmd/go/#hdr-Testing_flags

If, as in your case, you want to see the logs for tests that are not failing, you have to provide go test the -v flag (v for verbosity). More details on testing flags can be found here: https://golang.org/cmd/go/#hdr-Testing_flags

这篇关于您如何使用“测试"在 Go 测试中打印?包裹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆