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.
mock.Mockis testify mock.
helloNameis function mock.
TestMockHellois function testing.
new(useMock)create new struct for mock.
mock.Onto starting data mock. It will return 1 if we input
Mperas a user.
assert.Equalis for validation. We’re expecting that our mock will result
Hello 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?
if len(user) == 0with
if m.mock.helloName(user) == 0.
- Add struct
HelloUserto mock function
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