Practical complex data for unit testing
Tags: webdev, csharp, dotnet, testing
Published: 2021-09-09 12:44:28

<p>Unit testing is a long-established and essential part of the software development process&nbsp;particularly when using .NET.&nbsp; The basic premise, if you are not aware, is to test the public methods of classes so that they work as expected.&nbsp;</p>
<p>Unit tests follow the 3As: <em>Arrange</em>, <em>Act </em>and <em>Assert</em>. In other words, set up the conditions for the test, run the code and finally, check that it worked as expected. If it did, great the test passed!&nbsp; If not, then there&rsquo;s some work to do.</p>
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="https://ivwebsitestorprod.blob.core.windows.net/iv-website-files/c1_637662758481588575.png" alt="" width="404" height="325" /></p>
<p>This article takes a look at the first step, arranging the test.&nbsp; Although there are a few things to do during this stage, right now we are only concerned with creating the data required to run the test.</p>
<p>Later, we are going to look at how to create complex test data that can be easily understood by using the Builder pattern.</p>
<h2>Why is it important how test data is created?</h2>
<p>Well, the test data can be confusing to look at and to understand.&nbsp; It becomes time-consuming to follow and to update. This is especially the case where the test data has relationships to be maintained.&nbsp;</p>
<p>If the test data is not clear it is easy to make a mistake and introduce bugs into test code.</p>
<p>Test data which was written a long time ago becomes hard to recall.&nbsp; As with everything it is fresh in the mind when it is written, but three or six months later, it becomes difficult to recall the intent of the data.</p>
<p>It is easy and very tempting at times to break the <a title="Read about the DRY principle" href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself" target="_blank">DRY</a> (Don't Repeat Yourself)&nbsp;principle and just repeat test data.&nbsp; As new tests are set up, test data that is not well understood is typically copied and tweaked to suit the purpose.&nbsp; This just increases the technical debt within the test data making the whole project harder to maintain.</p>
<h2>Arranging test data</h2>
<p>Most, if not all code depends on parameters or data to run.&nbsp; So when it comes to unit testing and asserting that the code works some amount of data is usually required to run the test.&nbsp; This can range from a simple value-type parameter to a complex object model, or even a larger set of related data.&nbsp;</p>
<p>There are different ways of creating unit test data and we&rsquo;ll take a look at some of them briefly.</p>
<p>Test data can be created in a unit test directly, passed into a test in line, loaded from files, or created for use in an in-memory database. I consider in-memory database fine for unit testing.&nbsp; A separate database hosted outside the test execution process would be considered integration testing.</p>
<h2>Adding test data with xUnit Unit Test Framework</h2>
<p>To manage and run my unit tests I use <a title="xUnit website" href="https://xunit.net/" target="_blank">xUnit</a>. It is a popular, free, open source and community-focused unit testing framework. xUnit provides a few useful ways to manage our test data.</p>
<h3>Theory Unit Test</h3>
<p>Theory unit tests allow a single test to act on sets of parameterised data .&nbsp; Data is passed using the InlineData data attribute for as many different cases as needed.&nbsp; This keeps the test code DRY and removes the need to repeat the test logic for different data values.</p>
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="https://ivwebsitestorprod.blob.core.windows.net/iv-website-files/c2_637662776465999193.png" alt="" width="452" height="296" /></p>
<p>In cases where test data is complex, xUnit also supports ClassData and MemberData data attribute for loading test data in from a method or from another class.&nbsp; xUnit is extensible and custom data attributes can be written, for example, to <a href="https://andrewlock.net/creating-a-custom-xunit-theory-test-dataattribute-to-load-data-from-json-files/" target="_blank" rel="noopener">load test data from files</a> or from a database.</p>
<h3>Fixtures</h3>
<p>The final xUnit feature to look at is the Fixture class. Fixtures allow for sharing setup and clean up code for all tests in a class or even in multiple test classes.&nbsp; This is a great place to create complex test data and the perfect place for creating an in-memory database for the tests that require one.</p>
<p>For our development we often use SQL Server accessed via Entity Framework and to test we use SQLite in-memory database to simulate the database layer. We use this approach to initialise an in-memory database with the data we need which provides the context for a series of tests logically grouped in a class.</p>
<h3>AutoFixture</h3>
<p>One neat library for creating and generating test data is <a href="https://github.com/AutoFixture/AutoFixture" target="_blank" rel="noopener">AutoFixture</a>.&nbsp; The creators describe it as follows:</p>
<p><em>AutoFixture is an open source library for .NET designed to minimize the 'Arrange' phase of your unit tests in order to maximize maintainability. Its primary goal is to allow developers to focus on what is being tested rather than how to setup the test scenario, by making it easier to create object graphs containing test data.</em></p>
<p>We don&rsquo;t use AutoFixture for our test data creation in this example, but it is worth mentioning as it can speed up the process of writing tests.</p>
<h2>How the Builder Pattern can help create complex data</h2>
<p>As touched upon before, there are issues that emerge when test data gets complex.&nbsp; Thankfully there is an approach which we can use to help us and has been around for a long time.</p>
<p>The <a href="https://en.wikipedia.org/wiki/Builder_pattern" target="_blank" rel="noopener">builder pattern is a well-understood design pattern</a> in software development.&nbsp; It allows the construction of complex objects step by step and can be used to create different representations of complex data.</p>
<p>This is great for our needs as we can use this approach to create our test data.&nbsp; The builder pattern enables us to create our test data with the intent clear. It does mean creating a concrete implementation of the pattern using knowledge of the domain.&nbsp;</p>
<p>However, I think this approach can be worthwhile as it gives us the following benefits:</p>
<ul>
<li>Single place to instantiate objects</li>
<li>It leads to preventing the repetition of data</li>
<li>Provides a way of controlling each step of the construction process. This leads to the code providing a clear intent of the data.</li>
<li>The concrete implementation can be developed using domain-specific language. This also makes the intent of the data clearer. Name the builder methods as you wish to provide the most information to the developer/tester.</li>
<li>As the construction of the object is encapsulated in code, it can be designed so that foreign keys are handled in code which reduces complexity.</li>
<li>Also, it means collections are created when required. Collections can be navigated by accessing the last item by convention.</li>
</ul>
<h2>Builder Pattern In Action</h2>
<p>For this project I used .NET&nbsp;Core 5.0, EFCore and SQLite.&nbsp; Also included is xUnit for unit testing, AgileMapper for mapping and Fluent Assertions for the assertions.</p>
<p>Our <a href="https://github.com/JD-Innovensa/TestDataBuilderDemo" target="_blank" rel="noopener">demo project is a nascent itinerary planner and is available on GitHub</a>. It has a model based around tourists who have excursions containing visits to places (e.g. Paris) and visits to points of interests (e.g. Eiffel Tower).</p>
<p>The only bit of business logic is to swap the order of places to visit in an excursion.&nbsp; This logic is the code under test, has a dependency on a database and is encapsulated in a <code>TouristService</code>.</p>
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="https://ivwebsitestorprod.blob.core.windows.net/iv-website-files/c3_637662809038343271.png" alt="" width="691" height="449" /></p>
<p>So now for the data.&nbsp; As mentioned before, we will simulate a database using an in-memory SQLite database as this will work nicely with our service under test.&nbsp; This will be added using an xUnit fixture class so that all tests in the class can share the same data.&nbsp; Finally, we have our custom implementation of the builder pattern used to create the test data.</p>
<h3>What does the test builder look like?</h3>
<p>The <code>ITourist</code> interface contains methods to create our Tourist. You can see that the builder enables the complex object model to be built step by step using method names that have domain relevance. Finally the <code>BuildTourist</code> method will return our object.</p>
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="https://ivwebsitestorprod.blob.core.windows.net/iv-website-files/c4_637662809039652693.png" alt="" width="662" height="179" /></p>
<p>Now for a sample of the implementation.&nbsp;</p>
<p>Initially, we create our top-level object, a <code>Tourist</code> which is kept in a private field.</p>
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="https://ivwebsitestorprod.blob.core.windows.net/iv-website-files/c5_637662809039843065.png" alt="" width="643" height="270" /></p>
<p>Next, we add an <code>Excursion </code>to our tourist.</p>
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="https://ivwebsitestorprod.blob.core.windows.net/iv-website-files/c6_637662809040100964.png" alt="" width="629" height="275" /></p>
<p>All of the other steps are similar to the above to build up the object.</p>
<p>Finally, the <code>BuildTourist </code>method is implemented which returns our <code>Tourist</code>.</p>
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="https://ivwebsitestorprod.blob.core.windows.net/iv-website-files/c7_637662809040290097.png" alt="" width="236" height="81" /></p>
<p>The test project includes an example of loading the data using the Builder pattern.&nbsp; The order and indentation of items is important for readability, but not essential.</p>
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="https://ivwebsitestorprod.blob.core.windows.net/iv-website-files/c8_637662809040485764.png" alt="" width="619" height="276" /></p>
<p>For contrast, it also includes an example of loading the same test data by direct object creation.</p>
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="https://ivwebsitestorprod.blob.core.windows.net/iv-website-files/c9_637662809040706277.png" alt="" width="704" height="246" /></p>
<p>Comparing these two different implementations it is easy to see that using a Builder, the test data is more readable and easier to maintain.</p>
<p>Now on to the unit tests.&nbsp; The <code>TestsWithFixtureAndBuilder </code>class uses the Fixture where our test data is created.&nbsp; The test class contains a single test to check that the <code>SwapPlaceVisits </code>method works as expected.</p>
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="https://ivwebsitestorprod.blob.core.windows.net/iv-website-files/c10_637662809041203367.png" alt="" width="642" height="642" /></p>
<p>Remember to check out the <a href="https://github.com/JD-Innovensa/TestDataBuilderDemo" target="_blank" rel="noopener">entire code example in GitHub</a>.</p>
<h2>Further ideas for the Test Data Builder</h2>
<p>As this is custom code, there is a huge amount of flexibility available and you can enhance the basic test data builder to:</p>
<ul>
<li>Include validation rules. This can be useful for ensuring the business logic constraints are correct before running a test and ensuring your test data is correctly formed.</li>
<li>Set the primary keys automatically. Depending on how the tests are set up in your specific case, there could be the chance to set the primary keys in the builder.</li>
<li>Create model with default values and update specific values only. This can be done using lambda functions.</li>
<li>Add plain English descriptions to the builder and override the ToString() method. Textual information can be added inline.&nbsp; &nbsp;This could also be outputted during unit test execution to help debug problematic tests.</li>
<li>Add factory methods to generate common test data.</li>
</ul>
<h2>Conclusion</h2>
<p>As we&rsquo;ve seen, there are many ways of creating test data. However, when the data starts to become complex it can become difficult to understand and maintain and lead to complications with our unit tests.&nbsp; The builder pattern has been around for a long time and it has proven to be useful when creating test data to give context and make the test data easy to understand and maintain.</p>
<p>Hopefully this article and code example will provide some useful pointers to building your test data.&nbsp; Beyond this specific code example, the take home points are to find the approach which works best for you and the rest of your development and testing team.&nbsp; So when creating test data, aim for the following:</p>
<ul>
<li>The test data is easy to understand.</li>
<li>The relationship of the data is easy to understand.</li>
<li>The data is easy to change or add.</li>
<li>The approach ensures developers stick to the DRY principle.</li>
</ul>
<p>&nbsp;</p>