【问题标题】:Mocking open in go…在 go 中模拟打开…
【发布时间】:2020-09-22 01:08:01
【问题描述】:

我一直在关注this answer 试图模拟打开。我完全不知道在哪里。

这是我的测试代码:

func (m mockedFS) Open(name string) (file, error) {
    if m.reportErrOpen {
        return nil, errors.New("Fake failure")
    }
    mockedFile := mockIORead{}
    mockedFile.On("ReadAll", mock.AnythingOfType("[]uint8")).Return(0, fmt.Errorf("error reading"))
    mockedFile.On("Read", mock.AnythingOfType("[]byte")).Return(0, errors.New("NON"))
    return mockedFile, nil
}

type mockIORead struct {
    mock.Mock
    reportErr  bool  // Tells if this mocked FS should return error in our tests
    reportSize int64 // Tells what size should Stat() report in our test
}

func (m mockIORead) Read(b []byte) (n int, err error) {
    if m.reportErr {
        return 0, errors.New("A fake failure")
    }
    s := "Fear the old blood"
    copy(b[:], s)
    return 0, nil
}

func (m mockIORead) Close() error {
    return nil
}

func (m mockIORead) ReadAt([]byte, int64) (int, error) {
    return 0, nil
}

func (m mockIORead) Seek(int64, int) (int64, error) {
    return 0, nil
}

func (m mockIORead) Stat() (os.FileInfo, error) {
    if m.reportErr {
        return nil, os.ErrNotExist
    }
    return mockedFileInfo{size: m.reportSize}, nil
}

func TestOok(t *testing.T) {
    oldFs := fs
    // Create and "install" mocked fs:
    mfs := &mockedFS{}
    fs = mfs
    // Make sure fs is restored after this test:
    defer func() {
        fs = oldFs
    }()
    mfs.reportErr = false
    mfs.reportErrOpen = false
    token, err := Ook("fake")
    assert.NotNil(t, err)
    assert.Equal(t, "Fear the old blood", token)
}

这是正在测试的代码:

func Ook(name string) (string, error) {

    _, err := fs.Stat(name)
    if err != nil {
        return "", nil
    }

    file, err := fs.Open(name)
    if err != nil {
        return "", errors.Wrap(err, "Cannot open token file")
    }
    defer file.Close()

    _, err = ioutil.ReadAll(file)
    fmt.Print("PING\n")
    if err != nil {
        return "", errors.Wrap(err, "Could not read token")
    }
    return "Fear the old blood", nil
    //return string(token), nil
}

我到底做错了什么?

【问题讨论】:

  • “我到底做错了什么?”可能不是您正在寻找的答案,但主要问题是您尝试完全模拟文件系统。如果您的测试真的在没有 文件系统的机器上运行,这是必须做的事情,但它也真的不常见。刚刚从 fs 中读取。这很好,即使在测试中。无需嘲笑一切。 (你也不模拟 RAM 和 CPU)。
  • 您在Ook() 函数中使用的fs 是什么?还有mockIORead.Read()必须返回读取的字节数,copy()返回的数字!
  • @icza 与您的answer 中使用的相同。

标签: go


【解决方案1】:

第一个错误是您的mockIORead.Read() 返回错误值。它必须返回读取字节数(写入 slice 参数的字节数)(例如 copy() 将返回的内容)。

接下来,mockIORead.Read() 必须是有状态的! Reader.Read() 可能会被调用多次,不能保证传递的切片可以容纳您想要返回的所有数据(通过传递的b 切片)。

所以mockIORead 必须存储你想要返回的数据,并且它必须记住到目前为止已经传递了多少数据,这样下一个Read() 调用就可以从那里继续。

一个简单的实现是利用bytes.Buffer:

type mockIORead struct {
    mock.Mock
    reportErr  bool  // Tells if this mocked FS should return error in our tests
    reportSize int64 // Tells what size should Stat() report in our test

    content *bytes.Buffer
}

当返回这样的mockIORead时,用你希望返回的内容初始化content:

func (m mockedFS) Open(name string) (file, error) {
    if m.reportErrOpen {
        return nil, errors.New("Fake failure")
    }
    mockedFile := mockIORead{
        content: bytes.NewBufferString("Fear the old blood"),
    }

    return mockedFile, nil
}

并且由于可用的bytes.Buffer.Read() 方法,mockIORead.Read() 的实现可以像这样简单:

func (m mockIORead) Read(b []byte) (n int, err error) {
    if m.reportErr {
        return 0, errors.New("A fake failure")
    }
    return m.content.Read(b)
}

Ook() 函数本身不应该尝试“统计”,因为您没有模拟它(因此调用原始的 os.Stat() 可能会为测试中使用的 "fake" 文件名产生错误):

func Ook(name string) (string, error) {
    file, err := fs.Open(name)
    if err != nil {
        return "", errors.Wrap(err, "Cannot open token file")
    }
    defer file.Close()

    token, err := ioutil.ReadAll(file)
    fmt.Print("PING\n")
    if err != nil {
        return "", errors.Wrap(err, "Could not read token")
    }
    return string(token), nil
}

以及测试代码:

func TestOok(t *testing.T) {
    oldFs := fs
    // Create and "install" mocked fs:
    mfs := &mockedFS{}
    fs = mfs
    // Make sure fs is restored after this test:
    defer func() {
        fs = oldFs
    }()

    mfs.reportErr = false
    mfs.reportErrOpen = false
    token, err := Ook("fake")
    assert.Nil(t, err)
    assert.Equal(t, "Fear the old blood", token)
}

这会产生一个成功的(“OK”)测试。

【讨论】:

  • 谢谢!这不仅很清楚,而且也很有用。 :+1:
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-30
  • 2015-03-08
  • 1970-01-01
  • 2019-11-07
  • 2014-02-27
  • 2020-01-06
  • 1970-01-01
相关资源
最近更新 更多