Article thumbnail

Mocking up with factories

4m
patterns
practices

Intro

A quick tutorial of a factory method pattern that will reduce the headache connected with mocks creation in tests and applications.

Prelude

Mocking is a common practice during application testing, and sometimes also in application logic (when backend is not ready yet).

In this article we will explore best practices for mocks creation.

1. The problem

Imagine the situation when you have two endpoints:

  • get/users
  • /get/users/:id

Both of them return the same entity - user object. That object can be described with following interface:

Loading

Nothing fancy. When you call these API's, they will return list of users and user by id. So let's use a typical UI/logic implementation for this.

Loading

If you will have more layers in your architecture, it will be more complicated. In addition, there will be a need to apply same mocks in tests.

Loading

So where is the problem? Think about that in perspective of code maintenance. If you want to change the shape of an object you need to change every place in app where this object is imported and used. Also, this is the same instance of object so you can mess up your tests.

2. Factories for the rescue

Factory method is a simple design pattern which reduces complexity of object creation and moves this logic to separate, encapsulated code.

So instead of importing static object, we will import a function (factory method) which will create this object for us based on configuration or chained methods call.

Loading

You're using function to generate always new object. With factory you can chain methods to achieve object shape which you need.

Loading

Same for tests.

Loading

We have only 2 files but imagine the mess which you can avoid and time spend on refactor in bigger apps.

Summary

Nothing more to add. It's a really simple quick win. I'm using it in all of my projects. It also boosts development for green field projects when backend is not ready yet.

Feel free to contact me if you have any questions/proposals. Have a nice day and good health!

I create content regularly!

I hope you found my post interesting. If so, maybe you'll take a peek at my LinkedIn, where I publish posts daily.

Comments

Add your honest opinion about this article and help us improve the content.

created: 14-02-2023
updated: 14-02-2023