vendredi 22 septembre 2017

Golang - Testing - Fill os.Stdin for function that reads from it

How do I fill os.Stdin in my test for a function that reads from it using a scanner?

I request a user command line input via a scanner using following function:

func userInput() error {
    scanner := bufio.NewScanner(os.Stdin)

    println("What is your name?")
    scanner.Scan()
    username = scanner.Text()

    /* ... */
}

Now how do I test this case and simulate a user input? Following example does not work. Stdin is still empty.

func TestUserInput(t *testing.T) {
    var file *os.File
    file.Write([]byte("Tom"))
    os.Stdin = file

    err := userInput()
    /* ... */
}

Aucun commentaire:

Enregistrer un commentaire