Using GoMock

less than 1 minute read

Installation

go install github.com/golang/mock/gomock
go install github.com/golang/mock/mockgen

Generating Mocks

The syntax is:

mockgen -destination=<file> <package> <interface>

Say we want to mock a Servo interface part of the servo package:

mockgen -destination=mocks/mock_servo.go servo Servo

If we want to lump all of our mocks into one package called mocks, run:

mockgen -destination=mocks/mock_servo.go -package=mocks servo Servo

If servo is an external package, provide the full path:

mockgen -destination=mocks/mock_servo.go github.com/hoani/robogo/servo Servo

Mock Testing

Setting up mock objects

mockCtl := gomock.NewController(t)
defer mockCtl.Finish()

mockServo := mocks.NewMockServo(MockCtl)

Mock EXPECT

Asserts that MoveToAngle is called with angle 45.0 once. Will return true.

mockServo.EXPECT().MoveToAngle(45.0).
	Return(true).Times(1)

Asserts that MoveToAngle is called once, but doesn’t care what angle is provided. Will return true.

mockServo.EXPECT().MoveToAngle(gomock.Any()).
	Return(true).Times(1)

Times(n) can be replaced with:

  • MinTimes(n) or MaxTimes(n)
  • AnyTimes() when we don’t care if/how often it gets called

Sometimes, we want to take an action when a function is called:

mockServo.EXPECT().MoveToAngle(gomock.Any()).
	DoAndReturn(func(angle float32) bool {
		select {
			case <- ctx.Done():
				return false
			case angleCh <- angle:
				return true
		}	
	}).AnyTimes()