Member-only story

Fluent APIs and cleaner Unit Tests

Ali Ashoori
3 min readJan 26, 2020

This post and its examples use C# to demonstrate the solutions but the overall approach (or mindset) is applicable using other programming languages too.

In this post, we want to quickly consider one of the approaches used in writing Unit Tests which brings more readable code and sometimes they can also help with maintaining the code-base better. It’s a good way of abstraction that delegates the object initialization to different builder classes which correspond to different object models. Through the example below, you might find that this approach takes some effort where it needs the boilerplate code written for required object initialization in a test class.

But, I personally would prefer to take this approach as it brings a very nice abstraction and a cleaner code-base. Also, I have seen (and not really appreciate) initializing very complex immutable domain objects with numerous arguments passed to the constructors through test cases — and that it has made the code noisy and even hard to find where the actual logic of the test case (Act in AAA pattern) resides. Hence, based on the situation this could be a recommended approach.

The Example

This example simply displays the Fluent APIs against three different objects of Customer, Order, and Order Item.

--

--

Ali Ashoori
Ali Ashoori

Written by Ali Ashoori

Share to learn more, share to gain more..

No responses yet