How can stdout be captured or suppressed for Go(lang) testing?

后端 未结 4 2248
梦如初夏
梦如初夏 2021-02-20 04:32

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

4条回答
  •  猫巷女王i
    2021-02-20 05:26

    To suppress the output during the test I use the following code. I fixes output as well as logging. After test is done it resets the output streams.

    func TestStartStowWrongCommand(t *testing.T) {
     defer quiet()()   
     ...                      
    }
    
    func quiet() func() {
     null, _ := os.Open(os.DevNull)
     sout := os.Stdout
     serr := os.Stderr
     os.Stdout = null
     os.Stderr = null
     log.SetOutput(null)
     return func() {
      defer null.Close()
      os.Stdout = sout
      os.Stderr = serr
      log.SetOutput(os.Stderr)
     }
    }
    

提交回复
热议问题