drl37530 2018-12-07 15:24
浏览 51
已采纳

运行测试时如何丢弃打印输出

Using Go 1.11 I have a function that prints a label above a user input. This is fine and works but when I have started to write the test for this function it prints out this label when running the tests.

I have also use log.Print but then in the test file adding the following

func init() {
  log.SetOutput(ioutil.Discard)
}

This stops the log.Print from being displayed when running the tests. So how do I get it to do the same for any fmt.Println?

UPDATE

I thought I would post the func that I am testing and how I set up,

func checkLoop(loopCount int) int {
  var input int
  var ok bool

  for !ok {
    fmt.Printf("Input %d  ::  ", loopCount)
    ok, input = takeInput()
  }

  return input
}

So takeInput() only takes the users input, using fmt.Scan and checks it to see if its within a set range I want. So it returns a bool and if its false it will re-use the label to check what input number it is.

  • 写回答

3条回答 默认 最新

  • dpyoh6553 2018-12-07 17:32
    关注

    For example,

    discard_test.go:

    package main
    
    import (
        "fmt"
        "os"
        "syscall"
        "testing"
    )
    
    func printLabel(label string) {
        fmt.Println(label)
    }
    
    func TestDiscardLabel(t *testing.T) {
        defer func(stdout *os.File) {
            os.Stdout = stdout
        }(os.Stdout)
        os.Stdout = os.NewFile(uintptr(syscall.Stdin), os.DevNull)
        printLabel("Discard:")
    }
    
    func TestPrintLabel(t *testing.T) {
        printLabel("Print:")
    }
    

    Output:

    $ go test discard_test.go -v
    --- PASS: TestDiscardLabel (0.00s)
    === RUN   TestPrintLabel
    Print:
    --- PASS: TestPrintLabel (0.00s)
    PASS
    $ 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题