<p>In <code>$GOPATH/src/my_app/foobar</code> I can't run <code>go test</code> because <code>foobar_test.go</code> requires access to constants declared in the <code>main</code> package (to initialize databases etc). I have tried importing <code>main</code> in <code>foobar_test.go</code>, but it says it can't find main in <code>vendor</code>, <code>GOROOT</code> or <code>GOPATH</code>. I also can't use <code>foobar</code> package constants declared in other files, for the same reason.</p>
<p>I don't want to mock the database. How do I do this?</p>
<hr/>**评论:**<br/><br/>jerf: <pre><p>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</p>
<pre><code>func main() {
app := myapp.Application()
app.Run()
}
</code></pre>
<p>Anything that you find yourself needing somewhere else, pull it out of the "main" package.</p>
<p>A common pattern is to have the repo organized as</p>
<pre><code> maindir/
cmd/
application/
main.go
</code></pre>
<p>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.</p>
<p>[1]: This small stuff ends up pretty <em>messy</em>, 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.</p></pre>xrpfanboy: <pre><p>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.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传