douzhi1879 2016-07-25 09:03
浏览 234
已采纳

模拟bufio.NewScanner的标准输出流

I want to write a test for a utility function where I use bufio.NewScanner and Scan(). I usually use it on stdout and now I want to simulate a short piece of stream where I can return some static string for the purpose of the test.

bufio.NewScanner(r io.Reader) takes a Reader but that only requires a read method. By reading the source code I couldn't figure out from which buffer it reads or how that gets passed in.

How can I mock that in a short and concise way?

  • 写回答

2条回答 默认 最新

  • douzha8489 2016-07-25 10:32
    关注

    To simply test your code you can use @Sven's answer.

    To get an idea of a simple io.Reader for testing, consider below example:

    type R struct {
        Data string
        done bool
    }
    
    func (r *R) Read(p []byte) (n int, err error) {
        copy(p, []byte(r.Data))
        if r.done {
            return 0, io.EOF
        }
        r.done = true
        return len([]byte(r.Data)), nil
    }
    

    R is a custom test type that's implementing an io.Reader interface by having a Read method. Thus, it will be accepted by NewScanner. It can be used as:

    func NewR(data string) *R {
        return &R{data, false}
    }
    
    r := NewR("Test
    message
    ")
    scanner := bufio.NewScanner(r)
    
    for scanner.Scan() {
        fmt.Printf("Line: %s
    ", scanner.Text())
    }
    

    Output:

    Line: Test 
    Line: message
    

    Both the type R and its Read method have been defined to work as a simple source of bytes. Scan calls its reader's (input to NewScanner) Read method until it gets an EOF or an error. For simplicity, R's Read method copies its data to caller's buffer (p) in its first call and returns an EOF for any subsequent calls.

    Note that actual splitting of the lines at is done by scanner.Scan and not r.Read.

    You can modify the Read method above to get custom behavior as per your requirements.

    Working example: https://play.golang.org/p/zqDoQDIE93

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog