使用 JWT 声明对 .NET Core Web API 控制器进行单元测试
Unit Testing .NET Core Web API Controllers with JWT Claims
我正在尝试测试一种控制器方法,该方法利用 JWT 声明来获取客户端的用户名,如下所示:
[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();
// ...
}
但我非常幸运地尝试构思一种使用 Moq 和 XUnit 对上述控制器进行单元测试的方法。我搜索的很多问题都是直接设置controller的ControllerBase.User属性,但是在Aspnetcore.MVC(1.1.1)中,已经设置了User作为 只读.
我来这里有什么事?
Controller.User
只是 Controller.ControllerContext.HttpContext.User
的包装。首先模拟任何上下文:
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);
我正在尝试测试一种控制器方法,该方法利用 JWT 声明来获取客户端的用户名,如下所示:
[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();
// ...
}
但我非常幸运地尝试构思一种使用 Moq 和 XUnit 对上述控制器进行单元测试的方法。我搜索的很多问题都是直接设置controller的ControllerBase.User属性,但是在Aspnetcore.MVC(1.1.1)中,已经设置了User作为 只读.
我来这里有什么事?
Controller.User
只是 Controller.ControllerContext.HttpContext.User
的包装。首先模拟任何上下文:
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);