如何在Golang中测试日志记录(log.Println)?

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

How to test logging(log.Println) in Golang?

问题

如何在Golang中测试下面的代码?

  1. package main
  2. import "log"
  3. func main() {
  4. log.Println("hello world")
  5. }

请注意,测试Golang代码的一种常见方法是使用单元测试。您可以使用内置的testing包来编写和运行测试。以下是一个示例:

  1. package main
  2. import (
  3. "log"
  4. "testing"
  5. )
  6. func TestMain(t *testing.T) {
  7. log.Println("Running test...")
  8. main()
  9. // Add your assertions here
  10. }

在上面的示例中,我们使用testing包创建了一个名为TestMain的测试函数。在该函数中,我们首先打印一条消息以指示测试正在运行,然后调用main函数。您可以在TestMain函数中添加适当的断言来验证代码的行为是否符合预期。

要运行测试,请在终端中导航到包含测试文件的目录,并运行以下命令:

  1. go test

这将运行所有的测试函数并输出结果。

希望这可以帮助到您!如果您有任何其他问题,请随时问我。

英文:

How to test below the code in Golang?

  1. package main
  2. import "log"
  3. func main() {
  4. log.Println("hello world")
  5. }

答案1

得分: 0

你的程序将写入log包的标准记录器,该记录器将写入标准错误输出。编译并运行你的程序,查看标准错误输出中出现的内容。

英文:

Your program writes to the log package standard logger which writes to standard error. Compile and run your program and see what appears on standard error.

huangapple
  • 本文由 发表于 2017年4月3日 10:27:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/43175681.html
匿名

发表评论

匿名网友

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

确定