When writing unit testing it is always good practice to mock the database with test data to achieve the F.I.R.S.T principles of unit testing.
With only a few models in an application it is not too difficult to mock the necessary test data, but when your application grows it starts to become unmanageable. For example, can you imagine mocking data for an application with over 200 models?
A way of avoiding all the tedious work of generating all data required to test a certain method or unit of your application is taking advantage of factories, which by definition are responsible for “manufacturing” data when needed.
Making factories generator with TypeScript
While working on a TypeScript project I came across a library called factory.ts to generate model instances by interface or type definition.
Let’s say we have an interface IDepartment with two properties id and name, and we want to create a factory for our department interface. The only two things we need to do is to call the method makeFactory(); from the factory.ts library and then return an implementation of IDepartment.
So after creating the department factory you can reference the instance elsewhere on the application…
As the snippet above demonstrates, every time an instance of IDepartment is required you just need to invoke the build(); or buildList(); method from department factory and an instance will be provided. You can also easily override value of the interface properties when instantiating the factories by passing the desired properties as a parameter on the build() method.
Faking the factories
Generating random data for factories is great when it comes to testing the performance of your code with a big amount of data, or to simply populate a list with some random objects.
Going back to our example, we can easily generate a list of departments by assigning random data to the properties of the IDepartment interface. There are a ton of libraries that can help to create random data.
Notice that id and name properties are generated randomly by the library called faker.js. For more details about this library check out the documentation and its API which is very powerful.
Testing with factories
Once the factories are created, it is extremely easy to mock model instances to start testing our code.
The example above shows that with fewer lines of code, instances of IDepartment are provided to test the method getDepartment(); avoiding all hassle of creating the instances manually.
Conclusion
The example used in this blog was just to demonstrate the usage of creating factories. Indeed for small projects it can be a bit overwhelming, but as the application grows and unit testing is taken seriously in the project, the creation of factories comes in very handy, saving a lot of time and surely making testing easier.
References
ghsukumar/SFDC_Best_Practices F.I.R.S.T Principles of Unit Testing