fakeio is a small library to fake stdout/stderr/stdin. This is mainly for unit testing of CLI applications. Please see documentation for more details.
$ go get github.com/rhysd/go-fakeio Basic usage:
import ( "bufio" "github.com/rhysd/go-fakeio" ) // Fake stdout and input 'hello' to stdin fake := fakeio.Stdout().Stdin("hello!") defer fake.Restore() // Do something... // "hello!" is stored to variable `i` i, err := bufio.NewReader(os.Stdin).ReadString('!') // At this point, this line outputs nothing fmt.Print("bye") // "bye" is stored to variable `o` o, err := fake.String()Faking stderr:
fake := fakeio.Stderr() defer fake.Restore()Faking stdin:
fake, err := fakeio.Stdin("hello") defer fake.Restore()Faking stderr/stdout/stdin
fake := fakeio.Stderr().Stdout().Stdin("Faked input to stdin") defer fake.Restore()Reading as string:
s, err := fake.String() if err != nil { // Faking IO failed panic(err) } fmt.Println(s)Reading as bytes:
b, err := fake.Bytes() if err != nil { // Faking IO failed panic(err) } fmt.Println(b)Reading via io.Reader interface:
s := bufio.NewScanner(fake) for s.Scan() { // Reading line by line line := s.Text() fmt.Println(line) } if s.Err() != nil { // Error happened while reading panic(s.Err) }.Do() is a shortcut
s, err := fakeio.Stderr().Stdout().Do(func () { // Do something // Faked stderr and stdout are restored at exit of this scope }) if err != nil { // Faking IO failed panic(err) } fmt.Println(s)Please see examples for actual examples.