dongliang2058 2016-07-10 13:55
浏览 85
已采纳

如何测试ioutil.ReadFile和os.Stat?

I have the following function:

func GetDataFromFile(path string) ([]byte, error) {
    _, err := os.Stat(path)
    if err != nil {
        return nil, err
    }
    data, err := ioutil.ReadFile(path)
    if err != nil {
        return nil, err
    }
    return data, nil
}

I want to do tests for functions ioutil.ReadFile and os.Stat(path) when they throw errors. I know that I can create non-exist path for os.Stat(path), but how to test such kind functions without "workarounds" and guessing how functions are working?

Regards.

  • 写回答

2条回答 默认 最新

  • dongxing2302 2016-07-10 14:53
    关注

    I agree with abhink here, I would not expect you to test this particular function. But in practice, similar situation happens often.

    My best solution is to use a factory to create GetDataFromFile. In this case, you inject the dependencies.

    main.go

    package main
    
    import (
        "io/ioutil"
        "os"
    )
    
    func getDataFromFileFactory(
        stat func(filename string) (os.FileInfo, error),
        readFile func(filename string) ([]byte, error),
    ) func(path string) ([]byte, error) {
    
        return func(path string) ([]byte, error) {
            _, err := stat(path)
            if err != nil {
                return nil, err
            }
            data, err := readFile(path)
            if err != nil {
                return nil, err
            }
            return data, nil
        }
    }
    
    var GetDataFromFile = getDataFromFileFactory(os.Stat, ioutil.ReadFile)
    
    func main() {}
    

    main_test.go

    package main
    
    import (
        "errors"
        "os"
        "testing"
    )
    
    func TestGetDataFromFile(t *testing.T) {
        stat := func(filename string) (os.FileInfo, error) {
            return nil, errors.New("err msg")
        }
    
        readfile := func(filename string) ([]byte, error) {
            t.Error("should not call this function")
            return nil, nil
        }
    
        getDataFromFile := getDataFromFileFactory(stat, readfile)
    
        if _, err := getDataFromFile("foo"); err.Error() != "err msg" {
            t.Error("expected an error to be thrown")
        }
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办