简体   繁体   中英

how to mock user identity when testing web api controller with moq and nunit?

I would like to test web service call with user identity set ( pretending the user is logged in)

I have checked numerous posts and stackoverflow answers but I didn't quite get the answer I want.

The closest I got is this.

var context = new Mock<HttpContextBase>();
var mockIdentity = new Mock<IIdentity>();
context.SetupGet(x => x.User.Identity).Returns(mockIdentity.Object);
mockIdentity.Setup(x => x.Name).Returns("abc");

And at this point, I presume I have to set the controllercontext and that context variable needs to be fed somehow.

I have seen a lot of examples regarding MVCcontrollers but I couldn't find the one that works for an ApiController. Can someone please shed some light on this?

Thanks!

This is what I did for my project: For ASP.NET Web Api

this._userController.User = new ClaimsPrincipal(
                new ClaimsIdentity(
                    new List<Claim>
                    {
                        new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", "1234"),
                        new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", "Test@test.com"),
                        new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "live.com#Test@test.com")
                    })
                );

And this is for .net core web api:

var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
            {
                 new Claim(ClaimTypes.NameIdentifier, "testId"),
                 new Claim(ClaimTypes.Name, "testName")
            }));

        this.controller.ControllerContext = new Microsoft.AspNetCore.Mvc.ControllerContext()
        {
            HttpContext = new DefaultHttpContext() { User = user }
        };

Let me know if it helps or not.

Awww, It was so simple.

var identity = new GenericIdentity("bcd");

Controller.User = new GenericPrincipal(identity, null);

Turns out this part doesn't require mocking of the user, you just have to set the user ID of the controller you are calling.

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