Skip to content

Writing Tests that require JWT Authorization

williamlixu edited this page May 1, 2020 · 7 revisions

Test Setup

To get around JWT Authorization, and imitate already being logged in for when running tests, you need to set up a new HttpContext object for the Controller that is being tested and create a new identity for that HttpContext. There is now a HttpContextHelper class simplify this process.

The setup for this is as follows (this block needs to be placed in the [Setup] method of your test suite):

_context = _dbSetUpHelper.GetContext();
_httpContextHelper = new HttpContextHelper();

var httpContext = _httpContextHelper.GetHttpContext();
var objClaim = _httpContextHelper.GetClaimsIdentity();

_flatController = new FlatController(_context)
{
    ControllerContext = new ControllerContext
    {
        HttpContext = httpContext
    }
};

httpContext.User = new ClaimsPrincipal(objClaim);

Then, the user can be set for tests as follows (example for user with id of 999):

ClaimsIdentity objClaim = new ClaimsIdentity(new List<Claim> { new Claim(ClaimTypes.NameIdentifier, "999") });
_flatController.HttpContext.User = new ClaimsPrincipal(objClaim);

From there, in each of your tests you can call your controller field, and use it to call the different methods in the controller as normal.

Clone this wiki locally