C# 9.0 : Record Type Simplifies Unit Testing

C# 9 Record Type simplifies unit tests


Microsoft has released C# 9 with .NET 5.0. It has lots of new features. One feature I am particularly excited about is new Record Type in C# 9. We can now define our data classes with less code, and it looks clean.


Let’s consider a scenario where we have an API endpoint to create new Person in PersonsController. This endpoint takes a NewPersonRequest as parameter from post body. It then calls InsertPerson method of PersonService class.
InsertPerson method applies some business logic and transforms NewPersonRequest into Person database entity and send it to InsertPersonInD method of PersonRepository class, to insert it in the database. Repository method returns a Person with new Id if it successfully inserts it in the database. It returns null if not able to insert it.
InsertPerson method transforms Person in the PersonResponse and sends back to controller method. Which returns result to client.
We want to write a unit test for PersonService class's InsertPerson method.

Now Let’s Discuss Code:

Persons Controller:

Person Class:

New Person Request Class:

Person Response:

Person Service Interface:

Person Service Implementation

Person Repository Interface

Person Repository Implementation

Person Service Test class

Debug the Test:

Let’s now debug the test. Right click on the test method and select ‘Debug Test’ from the context menu. First break point is on the line where we are adding a mock setup for InsertPersonInDbStore method. We are setting up these values for newPerson variable which should be passed as a parameter for this method.

Mock person object
Mock person object


As we can see record type reduces not only coding time and number of lines, but also provides many other benefits. Read more about C# 9.0 features here. Please let me know if you have any thoughts about it in the comments below.

Developer, Blogger, Mathematician having 15+ years of experience in Software development and delivery using C#, ASP.NET, WebAPI, Angular etc.