dqby43944 2019-08-21 08:49
浏览 559

如何测试文件。使用os.O_RDWR和os.O_CREATE标志打开?

I'm trying to write unit test for struct constructor, which may return also nil if error happens during file.Open. I don't have idea how to test/mock file error with flags: os.O_RDWR|os.O_CREATE|os.O_APPEND

I tried to check nil value inside test, but it failed.

Constructor:

type App struct {
    someField string
    log *log.Logger
}

func New() *App {
    app := &App{}
    f, err := os.OpenFile("info.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
    if err != nil {
        fmt.Printf("error opening file: %v", err)
        return nil
    }
    mw := io.MultiWriter(os.Stdout, f)
    l = log.New(mw, "APP", log.Ldate|log.LstdFlags|log.Lshortfile)
    app.log = l

    return app
}

And test for constructor:

func TestNew(t *testing.T) {
    var a App
    a = New()

    // doesn't cover
    if a == nil {
        t.Fatal("Error opening file")
    }
}

I expect to have covered error != nil, which in coverage is red:

f, err := os.OpenFile("info.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
  fmt.Printf("error opening file: %v", err)
  return nil
}
  • 写回答

3条回答 默认 最新

  • dongqun5769 2019-08-21 09:21
    关注

    Mocking in Go means having interfaces, if that's something you really need you might consider using something like https://github.com/spf13/afero instead of using the os package directly. This also allows you to use in-memory filesystems and other things that make testing easier.

    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等