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

agolangf · · 388 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>In <code>$GOPATH/src/my_app/foobar</code> I can&#39;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&#39;t find main in <code>vendor</code>, <code>GOROOT</code> or <code>GOPATH</code>. I also can&#39;t use <code>foobar</code> package constants declared in other files, for the same reason.</p> <p>I don&#39;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 &#34;main&#34; 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&#39;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 &#34;anti-pattern&#34;, but it&#39;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&#39;s a nasty few screenfuls of code, it&#39;s still pretty small, even in relatively large applications.</p></pre>xrpfanboy: <pre><p>You can&#39;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

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