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

后端 未结 3 691
轮回少年
轮回少年 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:47

    You could consider adding a return statement to your function to return the string that is actually printed out.

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

    Now, your test could just check the returned string against an expected string (rather than the print out). Maybe a bit more in-line with Test Driven Development (TDD).

    And, in your production code, nothing would need to change, since you don't have to assign the return value of a function if you don't need it.

提交回复
热议问题