Testing: Mock Objects and Stubs

Nardiéna Althafia Pratama
HappyFresh Fleet Tracker
3 min readNov 8, 2019

In Unit Testing, units are being tested independently, so a better approach is to isolate the components undergoing the test using test doubles. Test doubles are any kind of pretend object that looks and behaves like their production equivalents, used in place of a real object for testing purposes. Using test doubles would help verify code independently from the rest of the system.

There are several kinds of Test Doubles used. In this article, I will be explaining about two kinds: Mock Objects and Stubs.

Mock Objects

Mock objects are objects that register calls they receive. When test assertions are used, we can verify on Mocks that all expected actions were performed.

We use these mocks when we don’t want to invoke production code or there isn’t an easy way to verify that the intended code was executed. These mocks allow us to set up scenarios without brining in large resources like databases. So in testing, instead of calling a database, you can simulate your database using a mock object in the unit test.

You can also make a generated mock object from the corresponding mocking tool you can use in your project. This is an example of how we did it in our project:

Generated Mock Object using Mockgen

We used Golang’s mocking tool, https://github.com/golang/mock, to generate a mock object as shown above. The mock object is then used in the code below:

Mock Objects Used in our Project

Like in the example above, the mock object doesn’t have to be generated from the mocking tool, some already exist (gomock.NewController() is used instead of the actual controller in the program).

Stubs

A stub is an object that contains predefined data and uses it to answer calls during tests. We use it when we can’t or don’t want to involve objects that would answer with real data or that would have undesirable side effects.

This is an example of how I have implemented stubs in my unit tests:

As you can see, we defined what the data that should be returned is.

That is all for this article. I hope you found my explanation useful!

Sources:

https://martinfowler.com/articles/mocksArentStubs.html#TheDifferenceBetweenMocksAndStubs

--

--