Create bufio interface from string in golang

huangapple go评论90阅读模式
英文:

Create bufio interface from string in golang

问题

我想在golang中为一个在构造函数中接受io.Reader的结构体编写单元测试。通常情况下,io.Reader接口来自于TCP连接。

现在我想使用预定义的字符串,并将其作为输入传递给io.Reader接口。

类似于:

s := "这是我的输入"
b := io.NewReader(s)
t := NewTestStruct(b)
t.doSomething()
英文:

I want to write unit tests in golang for a struct which accepts an io.Reader in the constructor. Usually the io.Reader interface is coming from a TCP connection.

Now I want to use a predefined string and use this as input to the io.Reader interface.

Something like:

s := "this is my input"
b := io.NewReader(s)
t := NewTestStruct(b)
t.doSomething()

答案1

得分: 6

strings.Reader 实现了 io.Reader 接口。你可以使用 strings.NewReader 来构造一个新的实例:

s := "this is my input"
b := strings.NewReader(s)
t := NewTestStruct(b)
t.doSomething()
英文:

strings.Reader implements the io.Reader interface. You can construct a new instance of it using strings.NewReader:

s := "this is my input"
b := strings.NewReader(s)
t := NewTestStruct(b)
t.doSomething()

答案2

得分: 5

这应该是正确的方式:

reader := bufio.NewReader(strings.NewReader("一些字符串"))
英文:

This should be correct way:

reader := bufio.NewReader(strings.NewReader("some string"))

huangapple
  • 本文由 发表于 2015年9月3日 03:32:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/32361627.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定