首页 > 解决方案 > 如何为从标准输入读取的内容编写 go Test 函数?

问题描述

我有类似这样的测试代码:

func TestRollback(t *testing.T) {

  store := NewStore()
  
  // do some stuff

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

问题是 store.Rollback() 提示从标准输入读取 y 或 n

运行时如何将“y”发送到测试进程go test -v --run TestRollback

标签: gotestingmockingstdin

解决方案


测试您的方法的困难Rollback源于硬编码它对 singleton 的依赖os.StdinTinkerer 的答案是可行的,但是因为它改变了包级别的变量,所以它不适合并行运行测试。

一种优选的替代方案(IMO)在于使用接口。在 Go 中,测试通常与接口押韵。在这里,因为os.Stdin满足io.Reader接口,您可以通过传递给您的工厂函数来参数化您的Store类型:io.Reader

type Store struct {
  // other fields, omitted here
  in io.Reader
}

func NewStore(in io.Reader) *Store {
  store := Store {
    // other fields, omitted here
    in: in,
  }
  return &store
}

然后,在您的测试函数中,您可以使用满足io.Reader且易于配置的具体类型,例如*strings.Reader

func TestRollback(t *testing.T) {
  // arrange
  in := strings.Reader("-- put contents of stdin here --")
  store := NewStore(in)
  // act
  err := store.Rollback()
  // assert
  // ...
}

推荐阅读