go - 如何为从标准输入读取的内容编写 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
解决方案
测试您的方法的困难Rollback
源于硬编码它对 singleton 的依赖os.Stdin
。
Tinkerer 的答案是可行的,但是因为它改变了包级别的变量,所以它不适合并行运行测试。
一种优选的替代方案(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
// ...
}
推荐阅读
- javascript - 我如何获得一个按钮来调用删除文本并用网格中的新文本替换它的 JS 脚本?
- wpf - 根据里面的Controls设置usercontrol大小
- javascript - 如何从画布上存储盒子?
- javascript - 在一个连接中将数据发送到不同的 websocket 端点
- spring-boot - logback.xml 在运行时更改配置
- javascript - setInterval 和 clearInterval 具有相同的按钮
- rest - 通过json发送附件文件
- docker - docker-compose 文件中的 shell 形式不调用命令 shell?
- c# - 初始化基类:两次声明一个变量?
- laravel - vuejs 和 laravel-vuejs 看不到组件的变化