One of the other issue you might encounter while unit testing your Controller is when you dealing with Identity. Consider the following action method.
public async Task<BarResponse> Foo(BarRequest user)
{
if (ModelState.IsValid)
{
try
{
var userName = User.Identity.Name;
// Do Task
return new BarResponse{
};
}
catch (Exception ex)
{
return new BarResponse { ErrorMessage = ex.Message};
}
}
else
{
var errrorMessages = ModelState.Values.SelectMany(x => x.Errors.Select(c => c.ErrorMessage));
return new BarResponse { ErrorMessage = string.Join(Environment.NewLine, errrorMessages), modelState = ModelState };
}
}
One of the issues is how do one mock the User.Identity.Name
. The trick lies in creating a Test instance of DefaultHttpContext
and replace with Controller’s context. Let’s write an Unit Test for the above code.
var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, "anuviswan"),
}, "mock"));
userController.ControllerContext.HttpContext = new DefaultHttpContext() { User = user };
Guess what, I spend atleast 5 hours for figuring out this. Some of the harder days in life.