Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
508 views
in Technique[技术] by (71.8m points)

Mocking open in go…

I have been following this answer trying to mock open. I have got exactly no where.

This is the test code I have:

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

And this is the code under test:

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
")
    if err != nil {
        return "", errors.Wrap(err, "Could not read token")
    }
    return "Fear the old blood", nil
    //return string(token), nil
}

What the hell am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...