Skip to content

Golang | Write Test with the Mock lib

Published: at 12:00 AM

Table of contents

Open Table of contents

Define a Test Object

// Robot
type Robot interface {
	SayHi()
}

// ServiceRobot is kind of Robot can offer services
type ServiceRobot struct {
}

func (robot *ServiceRobot) SayHi() {
	fmt.Println("Hi, I'm service robot")
}

// IndustrialRobot is kind of Robot can do some jobs
type IndustrialRobot struct {
}

func (robot *IndustrialRobot) SayHi() {
	fmt.Println("Hi, I'm industrial robot")
}

func StartRobots(){
	robots := initializeRobots()
	makeRobotsSayHi(robots)
}

// initialize all robots
func initializeRobots()[]Robot{
	robots := []Robot{
		&ServiceRobot{},
		&IndustrialRobot{},
	}
	return robots
}

// makeRobotsSayHi is used for making robots say hi
func makeRobotsSayHi(robots []Robot){
	for _, robot := range robots {
		robot.SayHi()
	}
}

Install mock tool

mockery provides the ability to easily generate mocks for golang interfaces. It removes the boilerplate coding required to use mocks.

go get github.com/vektra/mockery/.../

Mock the interface

$ $GOPATH/bin/mockery -name=Robot
Generating mock for: Robot in file: mocks/Robot.go

// Code generated by mockery v1.0.0. DO NOT EDIT.

package mocks

import mock "github.com/stretchr/testify/mock"

// Robot is an autogenerated mock type for the Robot type
type Robot struct {
	mock.Mock
}

// SayHi provides a mock function with given fields:
func (_m *Robot) SayHi() {
	_m.Called()
}

Write test

func TestMakeRobotsSayHi(t *testing.T){
	// create an instance of our test object
	mockRobotA := new(mocks.Robot)
	mockRobotB := new(mocks.Robot)

	// setup expectations
	mockRobotA.On("SayHi").Return(nil, nil)
	mockRobotB.On("SayHi").Return(nil, nil)

	robots := []Robot{
		mockRobotA,
		mockRobotB,
	}

	// Act
	makeRobotsSayHi(robots)

	// Assert that the expectations were met
	mockRobotA.AssertExpectations(t)
	mockRobotB.AssertExpectations(t)
}