Mock ULID using mock and Testify

blov · · 583 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hello Everyone,</p> <p>I have a method A that depends of a method B. I want to test method A, so Mock behaviour of B must be defined before the actual call. The problem is that method B generates an ULID based on time.Now() and with that i have been unable to generate B mock. --- Expected +++ Actual @@ -7,3 +7,3 @@ - ULID: (string) (len=0) &#34;&#34;, + ULID: (string) (len=26) &#34;01CCJH92SSQ1WDTF18KYJWXFCQ&#34;,</p> <p>Anyone has already faced that problem or have any advice that can help me? Thanks. </p> <hr/>**评论:**<br/><br/>quiI: <pre><p>It&#39;s kinda hard to understand your problem. </p> <p>Maybe put it on Go playground?</p> <p>If you&#39;re trying to control time in a test, simply inject it in as a dependency so you can control it. </p> <p><a href="https://play.golang.org/p/nNtlCAr2ITS" rel="nofollow">https://play.golang.org/p/nNtlCAr2ITS</a></p></pre>seomisS: <pre><p>I will follow your sugestion and ink=ject as a dependency</p></pre>sethammons: <pre><p>Can method B be an interface? </p> <pre><code>type IDGenerator interface { GenID(time.Time) string } </code></pre> <p>If you can have a property on your struct that is of type IDGenerator, then you can supply a fakeIDGen that matches the interface and always returns an expected value for tests. In the production code, you would pass a &#39;real&#39; IDGenerator that actually uses the passed in time to generate the ID.</p> <p>Not sure that this would work for your problem without more context. The other suggestion of supplying the time function works too.</p></pre>

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

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