GO-vatar series: Simple mock with Testify

Ferawati Hartanti Pratiwi
2 min readJul 16, 2020
https://www.pitodoble.com/imagenes/2011/02/nelson_muntz_ha_ha-400x390.jpg

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.

Create a struck for mock
Create a similar function to HelloUser function
Function to validate the mock

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 input Mper as a user.
  • assert.Equal is 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?

  1. Replace if len(user) == 0 with if m.mock.helloName(user) == 0.
  2. Add struct (m myStruct).
  3. myStruct directing HelloUser to mock function helloName.

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! .

Left image return 0 but expected Hello Mper!. Right image show an error that expectation and actual is not match.

--

--

Ferawati Hartanti Pratiwi

QA (Quality Ambassador) | mpermperpisang official Medium account