我需要模拟bufio Reader进行测试。特别是ReadString API。
func NewReader(rd io.Reader) *Reader
func (b *Reader) ReadString(delim byte) (string, error)
NewReader
返回bufio.Reader
。
由于它不返回抽象/接口,因此我无法为Reader创建适配器。
答案 0 :(得分:1)
您始终可以定义自己的界面
// An interface for the minimal api our code needs to work
type StringReader interface {
io.Reader
ReadString(delim byte) (string, error)
}
// Use dependency injection so that we can pass in a mock
// during testing
func DoSomething(r StringReader) error {
_, err := r.ReadString('x')
return err
}
// MockReader allows you to intercept calls to the
// underlying bufio.Reader
type MockReader struct {
bufio.Reader
ReadStringFunc func(delim byte) (string, error)
}
func (r *MockReader) ReadString(delim byte) (string, error) {
if r.ReadStringFunc != nil {
return r.ReadStringFunc(delim)
}
return r.Reader.ReadString(delim)
}
// The actual test
func TestDoSomething(t *testing.T) {
mr := MockReader{
Reader: bufio.NewReader(os.Stdin),
ReadStringFunc: func(delim byte) (string, error) {
if delim != 'x' {
t.Fatalf("want x, got %v", delim)
}
return "", nil
},
}
if err := DoSomething(mr); err != nil {
t.Fatal(err)
}
}