Unit testing controllers with User dependency on .Net Core

Photo by James Harrison on Unsplash

Trying .Net Core 5.0, I’ve set some playground rules. One of them is “let’s do this with Test Driven Development”, cool right?

After reading some pages about clean architecture I´ve defined a few projects:

  • Domain: a class lib project with some model classes
  • Domain.Tests.Unit: a Xunit project for Domain project-related unit tests
  • Application: a class lib project with some business logic classes
  • Application.Tests.Unit: a Xunit project for Application project-related unit tests
  • WebApi: a WebApi project with few Controller classes for the Request and Responses of my API
  • WebApi.Tests.Unit: a Xunit project for WebApi project-related unit tests

Nothing fancy!

Doing TDD for simple CRUD operations was very straight forward. Using Moq NuGet package for mocks and doing the // Arrange , // Act and // Assert approach the unit test seems like:

It’s a very simple test. And the Controller Action looks like this:

The code is also very simple. It gets the logged-in user’s email, creates the child model using that email, and asks the business logic to create it (very trivial in a lot of applications).

The problem

The User class, a ClaimsPrincipal class, available for you to get all the attributes from the logged-in users, is not directly accessible for you to set:

So how to define this data so I can make my test pass?

The way I solved it

The User class is defined when the controller’s HttpContext class is defined for the incoming request. So how to define the Claims when preparing the unit tests dependencies? the answer: when we instantiate a new controller:

and done, the user dependency is now ready to be enrolled on your TDD process.
Hope it helps!

Software Engineering Manager and Software Engineer | Server Side Trainer | Human stuff as a hobby.