How to test a function's output (stdout/stderr) in unit tests

后端 未结 3 703
轮回少年
轮回少年 2020-11-28 12:13

I have a simple function I want to test:

func (t *Thing) print(min_verbosity int, message string) {
    if t.verbosity >= minv {
        fmt.Print(message         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-28 12:30

    One thing to also remember, there's nothing stopping you from writing functions to avoid the boilerplate.

    For example I have a command line app that uses log and I wrote this function:

    func captureOutput(f func()) string {
        var buf bytes.Buffer
        log.SetOutput(&buf)
        f()
        log.SetOutput(os.Stderr)
        return buf.String()
    }
    

    Then used it like this:

    output := captureOutput(func() {
        client.RemoveCertificate("www.example.com")
    })
    assert.Equal(t, "removed certificate www.example.com\n", output)
    

    Using this assert library: http://godoc.org/github.com/stretchr/testify/assert.

提交回复
热议问题