Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Faking Azure AD Identity in ASP.NET Core Unit Tests

DZone's Guide to

Faking Azure AD Identity in ASP.NET Core Unit Tests

Unit testing ASP.NET apps that use Microsoft Azure AD usually means working with an authenticated user. Here's how to make one for your tests.

· Cloud Zone ·
Free Resource

Insight into the right steps to take for migrating workloads to public cloud and successfully reducing cost as a result. Read the Guide.

To have an Azure AD user available, we have to create a fake claims identity and fill it with claims that the test expects. Then we create the instance of a constructor and initiate the controller and HTTP context. The latter one contains identity.

Consider the following controller action.

public IActionResult Index()
{
    var name = User.Identity.Name;       // Do something with the name
 
    return View();
}


The test like this will probably fail with an exception, as there is no code that deals with the current user identity.

[Fact]
public void SampleTest()
{
    var controller = new HomeController();       controller.Index();
}


Let’s organize a typical claims identity with some claims to the controller.

[Fact]
public void SampleTest()
{
    var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
    {
            new Claim(ClaimTypes.NameIdentifier, "SomeValueHere"),
            new Claim(ClaimTypes.Name, "gunnar@somecompany.com")
            // other required and custom claims
    }));       var controller = new HomeController();
    controller.ControllerContext = new ControllerContext()
    {
        HttpContext = new DefaultHttpContext { User = user }
    };       controller.Index();
}


Now we have a fake claims identity available, which our controller will use. When running this test in Visual Studio, we can see that controller has the current user now.

aspnet-core-unit-test-claims-identity

It is also possible to use factory classes for identity. In this case, we have one class for production, which returns the current identity the controller has. Another class is for testing, and this class creates and returns fake identity. As I don’t see much benefit in using factories with no additional value, I suggest going with the directly created fake identity. Creating the identity can be moved to some helper method in the test class if it is needed in multiple tests.

TrueSight Cloud Cost Control provides visibility and control over multi-cloud costs including AWS, Azure, Google Cloud, and others.

Topics:
cloud ,azure ad ,unit testing ,asp.net ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}