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

func NewReader(rd io.Reader) *Reader
func (b *Reader) ReadString(delim byte) (string, error)
NewReader返回bufio.Reader
由于它不返回抽象/接口(interface),因此无法为Reader创建适配器。

能否请你帮忙。

最佳答案

您可以随时定义自己的界面

// 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)
  }
}

关于go - 模拟bufio外部软件包进行单元测试,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50803598/

10-10 04:32