Builder Pattern and Moq in Unit Tests

How to quickly set up test data in unit tests

Changhui Xu
codeburst
Published in
4 min readDec 7, 2020

--

The builder icon is made by Good Ware from www.flaticon.com; The MOQ icon is from its Git repository.

We regularly need to create some test data (or objects) for unit tests. A lot of unit tests only utilize a part of the input object and disregard the rest of the properties of the data object. For example, if a Person object contains a name, gender, birth date (and so on) and we want to write a unit test to check the calculation of a person’s age, we know that a person’s age only depends on the current date and the person’s birth date, and the person’s other attributes do not matter in this specific unit test. Therefore, for testing purposes, it would be handy if we could quickly create simple Person objects with desired birth dates and ignore other properties.

If we are strict about immutable objects (for example, hiding public setters), then constructing objects in a desired state can be cumbersome. A common approach to set up test data is using the Builder Pattern. We can adopt the builder pattern to write readable code. However, the builder pattern requires a ton of boilerplate code, and we also need to pay attention to the correctness of the builder classes.

This article explores whether there is an easier way to accomplish this job. First, I will first show you how the builder pattern works, then I will introduce a simple way to stage the test data…

--

--

Lead Application Developer. MBA. I write blogs about .NET, Angular, JavaScript/TypeScript, Docker, AWS, DDD, and many others.