SHARE:

Easy DataTable mocking for a simpler unit test in .NET Core

Introduction

Let’s face it, it all happened to us in our developer’s life to abandon a unit test because it was too tedious. For example the amount of data to mock was too great, but also, with some particularly heavy objects such as datatables are difficult to populate. Example of a DataTable containing only three records of three columns:

As you can see, if you have more columns and more rows, your test will be a complete mess.

In this article we will see how we can simplify this mess for a better and cleaner test. We will use XUnit, NSubstitute and ToExpectedObject for the demonstration

Scenario explanation

Let’s consider we want to test a TransactionService that consumes a TransactionRepository, this last one returns a DataTable. We need to mock this DataTable that contains three columns (Id, Amount and Date). Once done we want to be able to test the mapping made by TransactionService (DataTable to List‹Transaction›)

Transaction object signature:

Using JsonConvert.DeserializeObject

JsonConvert.DeserializeObject method (NewtonSoft) is able to deserialize JSON object to DataTable. Let’s build an helper that can open JSON files and deserialize it in any object (let’s make the helper generical in the meantime).

Setup Json files

Let’s create DataTable mock and Transactions mock within JSON files included as “Embedded files” in your test project.

DataTable mock:

List of transaction mock:

Coding the unit test

Once we have mocked your input data (DataTable) and the output expected (List of transactions), we are able to code our test.

Step 1 :

Let’s use the helper to arrange our mocks

Step 2:

Let’s configure the repository with NSubstitute to return our DataTable mock

Step 3:

Let’s invoke the transaction service to get the expected transactions

Step 4:

Invoke ToExpectedObject “ShouldEqual” assertion method

Conclusion

As you can see, we can make easy and readable unit tests by using JSON files to populate DataTable with JsonConverter class. Using external files makes this unit test not really isolated, but we can consider it’s acceptable because the data files are included in the test project as “Embedded files”, so the test doesn’t depend on real external resources. ToExpectedObject is also a real “plus”, because this library allow to compare objects by their values instead of their reference, many time I had pain to compare objects property by property….

Hope this article helped you to simplify your unit tests with DataTables. This article is also applicable to DataSets as well 😉

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.
%d bloggers like this: