<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 "testing"
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'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've been having lots of code that appears as if it'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't</em> the one being tested. It's showing you that the Get() method isn't tested because you aren't testing it. The RepoMock makes sense when you'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's not the interface that you want to test (because there's nothing to test), it'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'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
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传