Unit Test Web Api Controller fake ApiController.User with custom Identity doesn't work

Viewed 1226

I'm currently working with Web API v5.2.2 and I'm writing Unit Test code for one of the controllers. The problem I encountered was happening in ApiController.User part.

I have a custom Identity for the user implemented IIdentity Interface:

public class CustomIdentity : IIdentity
{
    //Constructor and methods
}

The CustomIdentity was set in the HttpRequest in normal usage. But since I'm only testing the query functionalities in the Unit Test, I just called the controller and its methods instead of sending requests.

Thus, I have to insert the User Identity into the Thread, and I tried with following ways:

var controller = new AccountsController(new AccountUserContext());

First try:

controller.User = new ClaimsPrincipal(new GenericPrincipal(new CustomIdentity(user), roles.Distinct().ToArray()));

And second try:

IPrincipal principal = null;

principal = new GenericPrincipal(new CustomIdentity(user), roles.Distinct().ToArray());

Thread.CurrentPrincipal = principal;

if (HttpContext.Current != null)
{
    HttpContext.Current.User = principal;
}

However, I got this error from both attempts:

Object reference not set to an instance of an object.

And I found the User identity remains null in the thread.

Anyone tried this method before? Thank you for the advice!

1 Answers
Related