Testing execution order of init()

agolangf · · 617 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Is there a way to get a test file&#39;s init() to execute before the main package&#39;s init()?</p> <p>EDIT for the curious: I&#39;m trying to write a test file that tests the behavior of the main package&#39;s init().</p> <hr/>**评论:**<br/><br/>hipone: <pre><p>Don&#39;t do important stuff in your init() for the very same reason you don&#39;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> (&#34;any&#34;) to <code>struct{}</code> (&#34;void&#34;). Although that would require a more verbose <code>return struct{}{}</code>, so maybe it&#39;s not a good idea after all. It&#39;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&#39;t proving that, and I can&#39;t test right now... Failing that you may have to use a build flag manually during testing.</p> <p>There&#39;s a bit of a code smell here. Perhaps you should let your user do the initializing. But it&#39;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&#39;s no test build flag, so it won&#39;t work.</p></pre>jerf: <pre><p>Then you can pass it in yourself.</p></pre>

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

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