【问题标题】:How to mock only one method of an interface如何只模拟接口的一种方法
【发布时间】:2019-11-16 08:15:53
【问题描述】:

我很难理解 Go 中的模拟(我正在寻找与 Go 中的 Java 等效的 Mockito.spy 相关的东西)。

假设我在 Go 中有一个带有 5 个方法的接口。但是我要测试的那段代码只引用了两种方法。现在如何在不实现所有方法的情况下模拟这种依赖关系,即我在源代码中的实际实现实现了 5 个接口方法,但是有没有办法避免在测试文件中实现 5 个方法的虚拟接口实现。以下是我目前正在做的方式,实现5个方法是可以管理的,但是如果接口有20个方法怎么办,模拟实现测试文件中的所有方法变得乏味。

示例:

handler.go 中的源代码:

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}
}

api.go中的源码:

 func processFeed(c Client) error {
     err := c.methodOne()
     if(err != null) {
      return err
    }
     err1 := c.methodTwo()
     if(err1 != null) {
      return err1
    }
 }

测试类代码:

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}


问题:

有没有办法只模拟我在上述情况下只需要 methodOne() 和 methodTwo() 方法,而不用担心测试中的剩余方法?如果存在,您能否建议任何其他替代方案?谢谢

【问题讨论】:

标签: unit-testing go mocking testify gomock


【解决方案1】:

首先,如果您的界面有 5 个方法,而您只使用一个,那么您的界面太大了。使用更小的接口。

type BigInterface interface {
    Thing1()
    Thing2()
    ThingN()
}

type SmallInterface interface {
    Thing1()
}

func MyFunc(i SmallInterface) { ... }

另一种选择是通过嵌入完整接口来创建完整接口的完整实现。如果您尝试访问其他方法之一,这将导致恐慌,但如果您小心,它将适用于测试。 (但请不要在生产代码中这样做!)

type BigInterface interface {
    Thing1()
    Thing2()
    ThingN()
}

type myImplementation struct {
    BigInterface
}

func (i *myImplementation) Thing1() { ... }

现在myImplementation 满足BigInterface 接口,因为它包含BigInterface 的嵌入式实例。如果您从未将该嵌入式实例设置为任何内容,那么调用这些方法将会出现恐慌,但您仍然可以定义 Thing1 来为您的测试做您想做的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多