Reputation: 195
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!
Upvotes: 4
Views: 1280
Reputation: 246998
You said
The CustomIdentity was set in the HttpRequest in normal usage.
Are you attaching a request to the controller when assembling your test.
Check the examples here
Unit Testing Controllers in ASP.NET Web API 2
[TestMethod]
public void QueryAccountControllerTest()
{
// Arrange
var user = "[Username Here]"
var controller = new AccountsController(new AccountUserContext());
//Set a fake request. If your controller creates responses you will need tis
controller.Request = new HttpRequestMessage {
RequestUri = new Uri("http://localhost/api/accounts")
};
controller.Configuration = new HttpConfiguration();
controller.User = new ClaimsPrincipal(new CustomIdentity(user));
// Act
... call action
// Assert
... assert result
}
Upvotes: 2