0

I have a function in GO that takes input from stdio and writes to stdio. Is there a way to write unit tests for the function?

An example function is:

func double() {
    var in int
    _, err = fmt.Scanf("%d", &in)
    if err==nil{
        fmt.Scanf(2*in)
    }
    else{
        log.Fatal("Error Scanning input")
    }
}

Note that in the real function I want to test, the I/O spans several lines so its not just as simple as making the result as an integer and return it. I am just giving the example here for reference.

AspiringMat
  • 2,161
  • 2
  • 21
  • 33
  • 3
    You don't unit test stdin, you make your implementation testable and independent from stdin. – JimB Nov 06 '17 at 14:53
  • 1
    Specifically, have the function take in an `io.Reader`, use `fmt.Fscanf`, and then pass it either stdin or an appropriate test Reader as necessary. – Adrian Nov 06 '17 at 14:55
  • @Adrian I am fairly new to GO. Do you mind giving me a reference where to start with these classes? – AspiringMat Nov 06 '17 at 14:58
  • 1
    I highly recommend reading the friendly manual: https://golang.org/pkg/io and https://golang.org/pkg/fmt would cover the interface and function I mentioned. – Adrian Nov 06 '17 at 15:00

0 Answers0