[英]Is there any way I can mock a Claims Principal in my ASP.NET MVC web application?
I've got some ASP.NET MVC
controller code that checks if a user is authenticated and if so, it checks to see if it has a specific claim.我有一些ASP.NET MVC
controller 代码检查用户是否经过身份验证,如果是,它会检查它是否有特定的声明。 Works fine.工作正常。
I've got some unit tests and I need to mock out an IPrincipal
(which is easy to do)... but I'm not sure how to check for the claims!我有一些单元测试,我需要模拟一个IPrincipal
(这很容易做到)......但我不知道如何检查索赔! I usually do something like我通常会做类似的事情
public static ClaimsPrincipal ClaimsPrincipal(this Controller controller)
{
return controller.User as ClaimsPrincipal;
}
and some controller code...和一些 controller 代码......
this.ClaimsPrincipal().HasClaim(x => x.......);
but this all fails when I test this in my Unit Test.. because I'm not sure how I can mock
the ClaimsPrincipal
但是当我在单元测试中对此进行测试时,这一切都失败了。因为我不确定如何mock
ClaimsPrincipal
Any ideas?有任何想法吗?
Mocking the ClaimsPrincipal isnt too difficult 模拟ClaimsPrincipal并不困难
var cp = new Mock<ClaimsPrincipal>();
cp.Setup(m => m.HasClaim(It.IsAny<string>(),It.IsAny<string>()))
.Returns(true);
However depending on how your controller gains access to it will. 但是,将取决于您的控制器如何访问它。 Have a look at this Question How to mock Controller.User using moq 看看这个问题如何使用moq模拟Controller.User
which would give you something like this: 这会给你这样的东西:
var cp = new Mock<ClaimsPrincipal>();
cp.Setup(m => m.HasClaim(It.IsAny<string>(), It.IsAny<string>())).Returns(true);
var sut = new UtilityController();
var contextMock = new Mock<HttpContextBase>();
contextMock.Setup(ctx => ctx.User).Returns(cp.Object);
var controllerContextMock = new Mock<ControllerContext>();
controllerContextMock.Setup(con => con.HttpContext).Returns(contextMock.Object);
sut.ControllerContext = controllerContextMock.Object;
var viewresult = sut.Index();
I am not sure what you mean with "mock". 我不确定您对“模拟”的含义。 But you can simply create a ClaimsPrincipal from scratch. 但是您可以简单地从头开始创建ClaimsPrincipal。 First create a ClaimsIdentity - add the claims and authentication method you need. 首先创建ClaimsIdentity-添加所需的声明和身份验证方法。 Then wrap it with a ClaimsPrincipal. 然后用ClaimsPrincipal包装它。
而且大多数方法都是虚拟的,因此它们是可模拟的。
you can declare and pass a real object as the follow example:您可以声明并传递一个真正的 object,如下例所示:
var controller = new ExampleController();
var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] {
new Claim(JwtClaimIdentifiers.Rol, "viewer"),
}, "Test"));
controller.ControllerContext = new ControllerContext();
controller.ControllerContext.HttpContext = new DefaultHttpContext { User = user };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.