In this post, I am going to show how to unit test the business layer of the lead microservice that I am developing. A couple of things to keep in mind to write the unit test for the business layer.
- These tests run must very fast for quick feedback.
- Only the business layer is involved and hence the web layer and repository layer should not be started. In other words, the Spring web tier beans should not be created and neither any database connections should be used. (This helps to achieve #1).
- The repository layer will be mocked using Mockito.
- The fluent assert from AssertJ library will be used.
The source code of the lead business unit test is shown in listing below.
Most of the test methods are straight forward. However, the testDelete the method needs some explanation. Here the findOne method is mocked/stubbed. This ensures that correct lead object is returned by the stub method. The other thing to note is that the verify the method for saving method captures the internal Lead object. Finally, that object is checked to verify that the "id" and "deleted" attributes. This ensures that the correct object was marked for soft delete by changing the "deleted" attribute.
I will pause the microservices test series for couple weeks. In the next post, I will write again about "12-factor app" and then introduce Spring Cloud Config Server and see how we can implement one key factor of cloud-native application. So, stay tuned.
The source code is available at - https://github.com/kdhrubo/playground/tree/develop/lead-backend