简体   繁体   中英

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. 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! I usually do something like

public static ClaimsPrincipal ClaimsPrincipal(this Controller controller)
{
    return controller.User as ClaimsPrincipal;
}

and some controller code...

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

Any ideas?

Mocking the ClaimsPrincipal isnt too difficult

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

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. First create a ClaimsIdentity - add the claims and authentication method you need. Then wrap it with a ClaimsPrincipal.

而且大多数方法都是虚拟的,因此它们是可模拟的。

you can declare and pass a real object as the follow example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM