Search code examples
gotestingmockingstdin

How do I write a go Test function for something that reads from stdin?


I have go test code similar to this:

func TestRollback(t *testing.T) {

  store := NewStore()
  
  // do some stuff

  err := store.Rollback()
  
  // checks
}

The problem is store.Rollback() has a prompt read from the stdin for y or n

How do I send "y" to the test process when running go test -v --run TestRollback


Solution

  • The following can redirect stdin temporarily.

    rd,wr,err := os.Pipe()
    saved := os.Stdin
    os.Stdin = rd
    
    ... Test code feeds wr ...
    
    os.Stdin = saved