<p>Is there a way to get a test file's init() to execute before the main package's init()?</p>
<p>EDIT for the curious: I'm trying to write a test file that tests the behavior of the main package's init().</p>
<hr/>**评论:**<br/><br/>hipone: <pre><p>Don't do important stuff in your init() for the very same reason you don't flag.Parse() in init() of the main package when it has tests.</p>
<p>Separate the logic to a global function and call it from main().</p></pre>vietnq: <pre><pre><code>var _ = myInit()
func myInit() interface{} {
// do something
return nil
}
</code></pre></pre>sh41: <pre><p>Looks great, I would change the return type from <code>interface{}</code> ("any") to <code>struct{}</code> ("void"). Although that would require a more verbose <code>return struct{}{}</code>, so maybe it's not a good idea after all. It's just style.</p></pre>drvd: <pre><p>Maybe you are overtesting or you are doing too much in init?</p></pre>jerf: <pre><ol>
<li>Define the init function as a separate function not named init.</li>
<li>Create a file in the package with a build flag !test, which contains an init function with one line that invokes the function you actually want.</li>
<li>When running the test, run it manually under circumstances of your choosing.</li>
</ol>
<p>I seem to recall the test build flag is set during tests, but some googling isn't proving that, and I can't test right now... Failing that you may have to use a build flag manually during testing.</p>
<p>There's a bit of a code smell here. Perhaps you should let your user do the initializing. But it's only a small and I can easily imagine valid use cases (initializing a binding to a C library, for instance). I just wanted to make sure this idea was out there.</p></pre>hipone: <pre><blockquote>
<p>Create a file in the package with a build flag !test</p>
</blockquote>
<p>There's no test build flag, so it won't work.</p></pre>jerf: <pre><p>Then you can pass it in yourself.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传