Mocks, Stubs, Fakes and Spy

Ayush Koshta
2 min readJul 5, 2021
Photo by Sigmund on Unsplash

All of us at some point of time in our lives have come across the confusion in terms of writing unit test cases. So in this post we’ll understand the different ways to mock the data we need to test the code.

Each and every unit test should follow AAA model (Arrange -Act-Assert)

  1. Arrange -Initialize the data which is required for the function.
  2. Act -Call our code which we are testing.
  3. Assert -Verify the result it is expected or not.

The actual code should not be modified to make the tests pass. The whole use case of unit test cases is if the function implementation changes the unit test cases should pass. To mock the data we make use of something called as test doubles.

Test Doubles

The use cases of test doubles can be as follows:

  1. Used in lieu of external dependencies ex: DB, API, Library.
  2. Whenever any error occurs we’ll get to know where the error is present.
  3. Can be used to simulate test scenarios by imitating the conditions.
  4. The different ways are Mocks, Stubs, Fakes, Spy etc.

Mocks

  1. Mocks can be treated as replacement of external interface.
  2. Let’s say you have a method which return the response from an API call, we can mock the result of that function.
  3. When your test case runs the framework should be responsible for not making the actual API call but to return the value from the mock.
  4. Production code should not be changed for mocks.
  5. Mocks are not used for checking function behavior or the return value.
  6. Basic use cases include-

Whether the function has been called or not

How many times it has been called

What parameters were used when the function was called

Stubs

  1. Generates predefined outputs.
  2. Can return success/failure/exception as coded.
  3. Checks the behavior of the code under test in case of these return values.

Fakes

  1. Fakes are almost working implementation of the actual code.
  2. Lets take an example where we query some data from a DB and we want to test some functionality out of it. With fakes, you will simulate this by creating a fake which can be an in memory DB, in memory table or your own local server.
  3. Fakes are created specifically for the particular test.
  4. For each and every unit test fakes can be recreated or unit test may share it.

Spy

  1. Spy always based on a real object with original methods that do real things.
  2. Can be used like a Stub to change return values of select methods.
  3. Can be used like a Mock to describe interactions.
  4. You create one real object and then you spy it. Now you can mock some methods and chose not to do so for some.

Hope we are little more clear on our previous understanding on the unit test cases and test doubles.

--

--

Ayush Koshta

Software developer by profession | Techno Utopian | Amateur Photographer