0

why fmt.Scanf doesn't work properly in a test file?

I have some test code as below, the test itself finishes without waiting for me to type in something.

I'm not simulating user input, the test needs someone to type with a keyboard while the it is running

package sometests

import (
    "fmt"
    "testing"
)

func TestScanf(t *testing.T) {
    fmt.Printf("type someting:\n")
    var s string
    fmt.Scanf("%s\n", &s)
    // test should wait here for me to type, but it won't
    fmt.Printf("you type: %q\n", s)
}
Nevercare
  • 81
  • 3
  • I don't know why Scanf doesn't work, but your tests should not depend on user input. You should be using Fscanf, or redirect stdin (perhaps `testing` already closes stdin?) – Jonathan Hall May 29 '18 at 08:33
  • change `Scanf` to `Fscanf` turns out the same result, maybe the `testing` already closes stdin. I'm testing a login method with a captcha input, which download a captcha image for me to read and send a post after waiting for me to type in the captcha string. is there a better way to test this method ? – Nevercare May 29 '18 at 08:46
  • I should have been more explicit: You should use Fscanf with a predefined io.Reader containing your input to test as input – Jonathan Hall May 29 '18 at 11:06
  • You can find your solution here : https://stackoverflow.com/questions/46365221/fill-os-stdin-for-function-that-reads-from-it – Amulya Kashyap May 29 '18 at 13:38

0 Answers0