A basic TDD example in Go

agolangf · · 451 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p><a href="https://github.com/jamesseanwright/golang-tdd-factorial" rel="nofollow">https://github.com/jamesseanwright/golang-tdd-factorial</a></p> <p>I&#39;ve been playing with Go for a while now and I wrote a very simple function for generating <a href="https://en.wikipedia.org/wiki/Factorial" rel="nofollow">factorials</a> using Test-Driven Development. You can see from the commit history how I&#39;ve written the tests first, satisfied them, and then refactored the code without causing any regressions.</p> <p>Any feedback is welcome and appreciated!</p> <hr/>**评论:**<br/><br/>tv64738: <pre><pre><code> expectedFactorial := 720 actualFactorial := GetFactorial(n) assertMatch(t, expectedFactorial, actualFactorial) </code></pre> <p>why not just</p> <pre><code> if g, e := GetFactorial(n), 720; g != e { t.Errorf(&#34;wrong factorial: %d != %d&#34;, g, e) } </code></pre></pre>swan--ronson: <pre><p>As funky as that is, I don&#39;t think it&#39;s as readable. Even setting aside the single letter variable names, I&#39;ve never enjoyed assignments in conditions. Good to know that this is possible though, thanks!</p> <p>That said, I&#39;d definitely be up for rewriting the assignments as follows:</p> <pre><code>expectedFactorial, actualFactorial := 720, GetFactorial(n) assertMatch(t, expectedFactorial, actualFactorial) </code></pre></pre>shovelpost: <pre><p>If single letter variable names are a problem then how about:</p> <pre><code>if got, want := GetFactorial(n), 720; got != want { t.Errorf(&#34;wrong factorial: %d != %d&#34;, got, want) } </code></pre> <p>For better or worse, this &#34;funky&#34; way is considered the <a href="https://golang.org/doc/faq#testing_framework" rel="nofollow">&#34;standard&#34; way of testing in Go</a>.</p></pre>swan--ronson: <pre><p>Actually, with more fleshed out variable names, this looks better. I like <code>got</code> and <code>want</code>; they&#39;re both short and descriptive. Thanks for your help!</p></pre>

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

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