Why Auto Fixture?

Shiljo Paulson
3 min readAug 8, 2021
Photo by Robin Thang on Unsplash

As you all might be aware in computer programming, unit testing is a software testing method by which individual units of source code — sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures — are tested to determine whether they are fit for use.

Arrange, Act, Assert Pattern (AAA) Pattern

The AAA (Arrange, Act, Assert) pattern/phase is a common way of writing unit tests for a unit test method.

Here is an example of how the unit test method looks in c# like incase if we follow AAA Style

Auto Fixture

The Primary use case of Auto Fixture is to simplify and reduce the arrange phase code. Now, let’s have a look in detail.

In case, if you have Model class with many properties it will be difficult to assign value to all the properties. Auto Fixture can help in randomly populating values to it. Let us see have refactored code using Auto Fixture.

If you debug and see the code what’s been populated for employee instance it will look like the below

For every string data type, it has prefixed the property name along with GUID. The Prefix with property name helps in identifying it. Also, if you notice I have used Without method to instruct not to populate values.

In real world scenario a FirstName or MiddleName cannot have digits and hypen(-) so how do we solve it to have predefined values.

here I have added

fixture.Inject<string>("Some Name");

then for all string data types it will generate “Some Name” as the string. So, if you use Inject method then for that specific type it will always set to same values.

Still not happy? then let’s change the code furthermore so that we get random alphabets for Name properties.

Here we have introduced a new class FixtureExtension for Fixture calls.

So here is how it is created.

You can read more about Auto Fixture at https://autofixture.github.io/docs/quick-start/

Yes, there are several other similar libraries and one of the libraries which is taking moment is FakeItEasy.

Please feel free to leave your valuable comments & do enjoy the coding.

--

--

Shiljo Paulson

Full stack Developer, good at OOPs, .Net, C#, TypeScript, JavaScript, SQL, HTML. Recent times interest is on Cloud, System Design and GoLang.