From 07a98a6dd448e0d3f6afd3945debee9c25ba23c8 Mon Sep 17 00:00:00 2001 From: Bruce Date: Wed, 26 Sep 2018 23:48:20 +0800 Subject: [PATCH] play interface --- playground/mocklib/mocks/Robot.go | 15 +++++++++++ playground/mocklib/robot.go | 45 +++++++++++++++++++++++++++++++ playground/mocklib/robot_test.go | 32 ++++++++++++++++++++++ 3 files changed, 92 insertions(+) create mode 100644 playground/mocklib/mocks/Robot.go create mode 100644 playground/mocklib/robot.go create mode 100644 playground/mocklib/robot_test.go diff --git a/playground/mocklib/mocks/Robot.go b/playground/mocklib/mocks/Robot.go new file mode 100644 index 0000000..3b4833d --- /dev/null +++ b/playground/mocklib/mocks/Robot.go @@ -0,0 +1,15 @@ +// 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() +} diff --git a/playground/mocklib/robot.go b/playground/mocklib/robot.go new file mode 100644 index 0000000..b3e0cc1 --- /dev/null +++ b/playground/mocklib/robot.go @@ -0,0 +1,45 @@ +package mocklib + +import "fmt" + +// 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() + } +} diff --git a/playground/mocklib/robot_test.go b/playground/mocklib/robot_test.go new file mode 100644 index 0000000..d02385e --- /dev/null +++ b/playground/mocklib/robot_test.go @@ -0,0 +1,32 @@ +package mocklib + +import ( + "github.com/weichou1229/go-patterns/playground/mocklib/mocks" + "testing" +) + +func TestStartRobots(t *testing.T) { + StartRobots() +} + +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) +}