GO-vatar series: Simple mock with Testify
A toolkit with common assertions and mocks that plays nicely with the standard library — https://github.com/stretchr/testify.
Mock is an approach to make sure if our code interacts well with other system modules when under testing. Using mock test, we can replace the module dependencies with something that can represent the real behavior.
So, first let’s create our function for demo.
That function is a simple way to greetings a user. What should we do next?
Let’s create our mock test.
The full code will be like this.
Explanation :
mock.Mock
is testify mock.helloName
is function mock.TestMockHello
is function testing.new(useMock)
create new struct for mock.mock.On
to starting data mock. It will return 1 if we inputMper
as a user.assert.Equal
is for validation. We’re expecting that our mock will resultHello Mper!
and that will proof that our data mock is correct.
Then we need to refactor our HelloUser
function to fit the mock.
What’s the difference?
- Replace
if len(user) == 0
withif m.mock.helloName(user) == 0
. - Add struct
(m myStruct)
. myStruct
directingHelloUser
to mock functionhelloName
.
Run
I’m using Visual Studio Code. So, I just need to click run test
to run function testing.
The result will be like this which means our mock and expectation has already appropriate.
Try to change the mock with return 0. In the function, if we input nothing (this means zero), then it should give an output like Hello Dude!
.
Keep calm and learning Go. — MperMperPisang
References :