A quick tutorial of a factory method pattern that will reduce the headache connected with mocks creation in tests and applications.
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:
Both of them return the same entity - user object. That object can be described with following interface:
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.
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.
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.
You're using function to generate always new object. With factory you can chain methods to achieve object shape which you need.
Same for tests.
We have only 2 files but imagine the mess which you can avoid and time spend on refactor in bigger apps.
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!