Mocking os.Stdin
You're on the right track that os.Stdin
is a variable (of type *os.File
) which you can modify, you can assign a new value to it in tests.
Simplest is to create a temporary file with the content you want to simulate as the input on os.Stdin
. To create a temp file, use ioutil.TempFile()
. Then write the content into it, and seek back to the beginning of the file. Now you can set it as os.Stdin
and perform your tests. Don't forget to cleanup the temp file.
I modified your userInput()
to this:
func userInput() error {
scanner := bufio.NewScanner(os.Stdin)
fmt.Println("What is your name?")
var username string
if scanner.Scan() {
username = scanner.Text()
}
if err := scanner.Err(); err != nil {
return err
}
fmt.Println("Entered:", username)
return nil
}
And this is how you can test it:
func TestUserInput(t *testing.T) {
content := []byte("Tom")
tmpfile, err := ioutil.TempFile("", "example")
if err != nil {
log.Fatal(err)
}
defer os.Remove(tmpfile.Name()) // clean up
if _, err := tmpfile.Write(content); err != nil {
log.Fatal(err)
}
if _, err := tmpfile.Seek(0, 0); err != nil {
log.Fatal(err)
}
oldStdin := os.Stdin
defer func() { os.Stdin = oldStdin }() // Restore original Stdin
os.Stdin = tmpfile
if err := userInput(); err != nil {
t.Errorf("userInput failed: %v", err)
}
if err := tmpfile.Close(); err != nil {
log.Fatal(err)
}
}
Running the test, we see an output:
What is your name?
Entered: Tom
PASS
Also see related question about mocking the file system: Example code for testing the filesystem in Golang
The easy, preferred way
Also note that you can refactor userInput()
to not read from os.Stdin
, but instead it could receive an io.Reader
to read from. This would make it more robust and a lot easier to test.
In your app you can simply pass os.Stdin
to it, and in tests you can pass any io.Reader
to it created / prepared in the tests, e.g. using strings.NewReader()
, bytes.NewBuffer()
or bytes.NewBufferString()
.