用于单元测试的mock bufio外部包

时间:2018-06-11 18:00:51

标签: go

我需要模拟bufio Reader进行测试。特别是ReadString API。

func NewReader(rd io.Reader) *Reader
func (b *Reader) ReadString(delim byte) (string, error)

NewReader返回bufio.Reader。 由于它不返回抽象/接口,因此我无法为Reader创建适配器。

你能帮忙吗?

1 个答案:

答案 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)
  }
}