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 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?