Test coverage when using interfaces

xuanbao · · 498 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Greetings,</p> <p>So I am trying to improve my testing. I read that using interfaces to mock dependencies is a very good technique. It is working very well but I am having a little problem with test coverage. </p> <p>I am having on my package file:</p> <pre><code>package example type Repo interface { Get() } type RepoClient struct{} func (r *RepoClient) Get() { // Code calling the real system. } </code></pre> <p>and the test file:</p> <pre><code>package example_test import &#34;testing&#34; type RepoMock struct{} func (r *RepoMock) Get() { // Test implementation } func TestGet(t *testing.T) { r := RepoMock{} r.Get() } </code></pre> <p>Despite the fact that I am testing the Get() method, it will still appear as if it&#39;s not tested in the test coverage results (which is only logical since func (r *RepoClient) Get() is never actually called in the tests). I am trying to have a good percentage of test coverage but ever since I started using interfaces to mock behavior, I&#39;ve been having lots of code that appears as if it&#39;s not tested. This got me thinking that maybe I am doing something wrong. Am I missing something?</p> <p>Thank you</p> <hr/>**评论:**<br/><br/>echophant: <pre><p>Mocking is useful when the component being mocked <em>isn&#39;t</em> the one being tested. It&#39;s showing you that the Get() method isn&#39;t tested because you aren&#39;t testing it. The RepoMock makes sense when you&#39;re trying to test something that would normally have a dependency on a RepoClient, but not when you want to test the functionality of the RepoClient itself. Here, it&#39;s not the interface that you want to test (because there&#39;s nothing to test), it&#39;s the actual implementation, the RepoClient.</p> <p>However, if you do need a RepoMock to use for other components that do depend on a Repo, it might make sense to test the RepoMock, if it&#39;s sufficiently complex to warrant it, in your opinion.</p></pre>gchaincl: <pre><p>What you need is a combination between integration testing (for testing your real implementation, and -coverpkg flag)</p></pre>drvd: <pre><p>Maybe you could write proper test for your code first and start worrying about testability and test coverage second?</p></pre>

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

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