Moz*_*zhi 1 unit-testing mocking go gomock testify
我正在努力理解 Go 中的模拟(我正在寻找与 Mockito.spy 相关的东西,相当于 Go 中的 Java)。
假设我在 Go 中有一个带有 5 个方法的接口。但是我要测试的这段代码只引用了两种方法。现在我如何在不实现所有方法的情况下模拟这种依赖关系,即我在源代码中的实际实现实现了 5 个接口方法,但是有没有办法避免在测试文件中实现 5 个方法的虚拟接口实现。以下是我目前的做法,实现5个方法是可以管理的,但是如果接口有20个方法,模拟实现测试文件中的所有方法变得乏味。
type Client struct {}
type ClientStore interface {
func(c *Client) methodOne() error {// some implementation}
func(c *Client) methodTwo() error {// some implementation}
func(c *Client) methodThree() error {// some implementation}
func(c *Client) methodFour() error {// some implementation}
func(c *Client) methodFive() error {// some implementation}
}
Run Code Online (Sandbox Code Playgroud)
func processFeed(c Client) error {
err := c.methodOne()
if(err != null) {
return err
}
err1 := c.methodTwo()
if(err1 != null) {
return err1
}
}
Run Code Online (Sandbox Code Playgroud)
import "testify/mock"
func TestFeed(t *testing.T){
mockClient := &MockClient{}
err := processFeed(mockClient)
assert.NotNil(t , err)
}
type MockClient struct {
mock.Mock
}
func(c *MockClient ) methodOne() error {fmt.Printf("methodOne");nil}
func(c *MockClient ) methodTwo() error {return errors.New("mocked error")}
func(c *MockClient ) methodThree() error {fmt.Printf("methodThree");nil}
func(c *MockClient ) methodFour() error {fmt.Printf("methodFour");nil}
func(c *MockClient ) methodFive() error {fmt.Printf("methodFive");nil}
Run Code Online (Sandbox Code Playgroud)
有没有办法只模拟我在上述情况下只需要的 methodOne() 和 methodTwo() 方法,而不用担心测试中的剩余方法?如果存在其他替代方案,您能否提出建议?谢谢
首先,如果你的接口有 5 个方法,而你只使用了一个,那么你的接口就太大了。使用较小的接口。
type BigInterface interface {
Thing1()
Thing2()
ThingN()
}
type SmallInterface interface {
Thing1()
}
func MyFunc(i SmallInterface) { ... }
Run Code Online (Sandbox Code Playgroud)
另一种选择是通过嵌入完整接口来创建完整接口的完整实现。如果您尝试访问其他方法之一,这将引起恐慌,但如果您小心,它将用于测试。(但请不要在生产代码中这样做!)
type BigInterface interface {
Thing1()
Thing2()
ThingN()
}
type myImplementation struct {
BigInterface
}
func (i *myImplementation) Thing1() { ... }
Run Code Online (Sandbox Code Playgroud)
由于包含 的嵌入实例,现在myImplementation满足BigInterface接口BigInterface。如果您从未将该嵌入式实例设置为任何内容,那么调用这些方法将导致恐慌,但您仍然可以定义Thing1为您的测试执行您想要的操作。
| 归档时间: |
|
| 查看次数: |
686 次 |
| 最近记录: |