dqwh1219 2014-04-21 20:27
浏览 167
已采纳

如何使用“测试”包在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")
}

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

ok      command-line-arguments  0.004s

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")
}

Which outputs this:

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.

  • 写回答

4条回答 默认 最新

  • dongqing904999 2014-04-21 20:50
    关注

    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.

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

    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.

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码