C# 9.0 : Record Type Simplifies Unit Testing



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.


It also provides synthesized methods to provide value semantics for equality. Which makes unit test verification lot easier. Without the Record Type, if we use Class to define entity and when a new instance is created in a service under test to pass it to another class’s method, then we need to use It.Is<T>(...) to provide which field values are equal in these instances or write Mock Verification to verify correct instance of the object was passed as parameter.


In this article I have described how C# 9.0 Record Type simplifies unit testing and mocking the dependencies.


Scenario:

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.

Note: Make sure Projects are using .NET 5.0 Framework.


Now Let’s Discuss Code:


Persons Controller:


[Route("api/[controller]")]    [ApiController]
public class PersonsController : ControllerBase    
{
    private readonly IPersonService _personService;
    public PersonsController(IPersonServicepersonService)        
    {
        _personService=personService;        
    }        
    [HttpPost]
    public IActionResult InsertPerson([FromBody] 
        NewPersonRequest newPersonRequest, 
        CancellationToken cancellationToken)        
    {
    var personResult =_personService.InsertPerson(newPersonRequest);