我想测试一个控制器方法,该方法利用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对上述控制器进行单元测试,但运气实在不好。我搜索的许多问题都涉及直接设置控制器的ControllerBase.User属性,但在Aspnetcore.MVC(1.1.1)中,User已被设置为只读。
那么我该怎么做呢?