I'm attempting to test a controller method that utilizes JWT claims to get the user name of the client like so:
[Authorize]
[Route("api/[controller]")]
public class ApprovalsController : Controller
{
// POST api/approvals
[HttpPost]
public IActionResult Post([FromBody]ApprovalViewModel value)
{
// ...
// Incoming approval VM converted here
Approval newApproval = TinyMapper.Map<Approval>(value);
// Values set server-side here.
newApproval.Id = -1;
newApproval.Created = DateTime.Now;
// Claim queried here
newApproval.CreatedBy = User.FindFirst(ClaimTypes.Name).Value;
// Submission to context
_approvalRepo.Insert(newApproval);
_approvalRepo.Update();
// ...
}
But I've had the darnedest luck in trying to conceive of a way to unit test the above controller using Moq and XUnit. Many of the questions I've searched for involve directly setting the ControllerBase.User attribute of the controller, but in Aspnetcore.MVC (1.1.1), User has been set as read-only.
What is it that I'm to do, here?
Controller.User
is just a wrapper of Controller.ControllerContext.HttpContext.User
. Mock any context first:
var controller = new HomeController();
var contextMock = new Mock<HttpContext>();
contextMock.Setup(x => x.User).Returns(new ClaimsPrincipal());
controller.ControllerContext.HttpContext = contextMock.Object;
Assert.NotNull(controller.User);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With