如何查看Go程序测试代码的堆栈跟踪?

huangapple go评论81阅读模式
英文:

How to see stack trace of test code of Go program?

问题

我使用Go的原生测试工具(go test)编写测试。但是当测试由于测试代码中的错误而失败时,由于缺乏堆栈跟踪或任何其他上下文信息,我真的无法进行调试。

而且,测试代码需要一个上下文对象t,所以在正常模式下运行测试代码并不是一件简单的工作。

调试测试代码的最佳实践是什么?

英文:

I use Go's native test facility (go test) to write a test. But when the test fails due to a bug in test code, I really can't debug it due to lack of stack trace or any other contextual informations.

And even, the test code needs one contextual object t, so it is not simple work running the test code in normal mode.

What is the best practice to debug test code?

答案1

得分: 9

你可以通过以下方式记录堆栈跟踪:

t.Log(string(debug.Stack()))

文档在这里:https://golang.org/pkg/runtime/debug/#Stack

PrintStack相比,它更好,因为它不会干扰常规的测试日志。

英文:

You can log stack trace this way

t.Log(string(debug.Stack()))

Documentation is here https://golang.org/pkg/runtime/debug/#Stack

It is better than PrintStack because it doesn't interfere with regular test logs.

答案2

得分: 5

你可以使用 t.Log() 来记录有关测试用例的信息——如果测试用例失败或者运行 go test -v,Go 会显示该输出。

你还可以使用 panic 来断言测试中的某些状态——如果测试发生 panic,你将在控制台中看到相应的跟踪信息。

英文:

You can use t.Log() to log information about the test case -- go will show that output if the test case fails or if you run go test -v

You can also assert certain state within the test using panics -- if a test panics, you will see the trace in your console.

答案3

得分: 2

我不知道你是否想要在代码中检查这个,但是对于一次性的调试,PrintStack可能会有帮助。你可以查看这个链接:http://golang.org/pkg/runtime/debug/#PrintStack

英文:

I don't know if you'd want to check in code with this in it, but for one-off debugging, PrintStack might help. http://golang.org/pkg/runtime/debug/#PrintStack

huangapple
  • 本文由 发表于 2013年11月4日 04:05:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/19757462.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定