dpde7365 2017-03-10 18:00
浏览 15
已采纳

在Go中模拟单个方法

In Go, how can I mock an interface without having to implement every method? Let's say I have a Car interface and a Corolla struct that implements that interface:

type Car interface {
    changeTire()
    startEngine()
    ....
    refuel()
}

type Corolla struct {
    ...
}

func (c Corolla) changeTire() {...}

func (c Corolla) startEngine() {...}

func (c Corolla) refuel() {...}

Let's say I also have a Garage struct that depends on Car:

type Garage struct {
    MyCar Car
}

func (g Garage) PrepareCarToDrive() {
    g.MyCar.changeTire()
    g.MyCar.refuel()
    g.MyCar.startEngine()
}

And I want to test Garage, so I create a MockCar that implements Car

type MockCar struct {
    ...
}

func (c MockCar) changeTire() {...}

func (c MockCar) startEngine() {...}

func (c MockCar) refuel() {...}

Now I have tests that test PrepareCarToDrive and I use the MockCar:

func TestGarage_PrepareCarToDrive_DoesSomething(t *testing.T) {
    mockCar := MockCar{}
    garageUnderTest := Garage{}
    garageUnderTest.MyCar = mockCar

    // some other setup

    // when Garage calls mockCar.changeTire(), should do X
    ...
}

func TestGarage_PrepareCarToDrive_DoesSomethingElse(t *testing.T) {
    mockCar := MockCar{}
    garageUnderTest := Garage{}
    garageUnderTest.MyCar = mockCar

    // some other setup 
    // when Garage calls mockCar.changeTire(), should do Y
    ...
}

My question is, how can I have mockCar do different things each test? I know that I can create a different mock implementation of Car for each test. But this will get out of hand really quickly as I add more methods to Car.

I'm coming from a Java background so I'm looking for something like Mockito that will let me mock just the methods I need for each test.

What is the best way to do this in Go? Or am I missing something more fundamental?

  • 写回答

2条回答 默认 最新

  • dongli8722 2017-03-10 19:57
    关注

    If you embed the interface type itself in your mock struct, you can then only implement the methods you need. For example:

    type MockCar struct {
        Car
        ...
    }
    
    func (c MockCar) changeTire() {...}
    

    Even though your struct only implements changeTire explicitly, it still satisfies the interface because the Car field provides the rest. This works as long as you don't try to call any of the unimplemented methods (which will cause a panic because Car is nil)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 CSS实现渐隐虚线边框
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题