[noob] How do I manage and import package data when testing?

agolangf · 2018-04-04 19:30:12 · 598 次点击    
这是一个分享于 2018-04-04 19:30:12 的资源,其中的信息可能已经有所发展或是发生改变。

In $GOPATH/src/my_app/foobar I can't run go test because foobar_test.go requires access to constants declared in the main package (to initialize databases etc). I have tried importing main in foobar_test.go, but it says it can't find main in vendor, GOROOT or GOPATH. I also can't use foobar package constants declared in other files, for the same reason.

I don't want to mock the database. How do I do this?


评论:

jerf:

My main packages typically end up very small [1], because I pull all of this out of them. There are some packages that are almost literally

func main() {
    app := myapp.Application()
    app.Run()
}

Anything that you find yourself needing somewhere else, pull it out of the "main" package.

A common pattern is to have the repo organized as

 maindir/
    cmd/
        application/
            main.go

so that the command is separated, and it doesn't feel too strange that main.go may actually be fairly small. Having the top level of the repo be a main package is not exactly an "anti-pattern", but it's suitable only for projects that will not grow beyond a certain size where the whole thing fits in one package comfortably.

[1]: This small stuff ends up pretty messy, because I put all the plumbing together of the components in my main function. But even though it's a nasty few screenfuls of code, it's still pretty small, even in relatively large applications.

xrpfanboy:

You can't import main package. Make sure your test uses package main as well and not something like main_test. You should be able to access variables inside the same package.


入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

598 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传