dopzc64662
2015-07-27 21:00
浏览 94
已采纳

如何在Go(lang)测试中捕获或抑制stdout?

How can stdout be captured or suppressed for Go testing?

I am trying to teach myself go(lang) testing. In the code below, myshow.LoadPath prints lots of information to stdout (which is a normal side effect). It does however make for very noisy output when I run "go test" Is there a way to suppress or capture stdout?

For comparison, I'm thinking about something like this from the python world. http://pytest.org/latest/capture.html#captures

package slideshow_test

import (
    "os"
    "testing"

    "github.com/golliher/go-hpf/slideshow"
)

func setupTest() {
    myshow := slideshow.Slideshow{Name: "This is my show"}
    myshow.LoadPath("..")

}

func TestStub(t *testing.T) {
    if true == false {
        t.Fail()
    }
}

func TestMain(m *testing.M) {
    setupTest()
    os.Exit(m.Run())

}

图片转代码服务由CSDN问答提供 功能建议

如何为Go测试捕获或抑制stdout?

我是 尝试自学go(lang)测试。 在下面的代码中,myshow.LoadPath将大量信息输出到stdout(这是正常的副作用)。 但是,当我运行“ go test”时,它的确产生了非常嘈杂的输出。有没有办法抑制或捕获stdout?

为了进行比较,我正在考虑python世界中的类似问题。 http://pytest.org/latest/capture.html#captures

 程序包slideshow_test 
 
import(
“ os” 
“测试” 
 
“ github.com/golliher/go-hpf/slideshow” 
)
 \  nfunc setupTest(){
 myshow:= slideshow.Slideshow {名称:“这是我的节目”} 
 myshow.LoadPath(“ ..”)
 
} 
 
func TestStub(t * testing.T  ){
 if true == false {
 t.Fail()
} 
} 
 
func TestMain(m * testing.M){
 setupTest()
 os.Exit(m.Run  ())
 
} 
   
 
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

  • dounuogong0358 2015-07-27 21:10
    最佳回答

    os.Stdout which is used by the fmt.Printf and others is just a variable. So you can overwrite it at any time and restore it back when necessary. https://golang.org/pkg/os/#pkg-variables

    评论
    解决 无用
    打赏 举报
查看更多回答(2条)

相关推荐 更多相似问题