vendredi 10 mars 2017

Mocking single methods in 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?

Aucun commentaire:

Enregistrer un commentaire