Testing .NET Core Web UI Modular Controllers with JWT Requirements

I'm trying to test a controller method that uses JWT claims to get the client's username like this:

[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 had my worst luck trying to present a way to unit test the above controller using Moq and XUnit. Many of the questions I was looking for are directly related to setting the ControllerBase.User attribute of the controller, but in Aspnetcore.MVC (1.1.1) the user was configured as read-only.

What should I do, here?

+3


source to share


1 answer


Controller.User

is just a wrapper Controller.ControllerContext.HttpContext.User

. First deflate any context:



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);

      

+1


source







All Articles