Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 652
rlee923 Avatar asked Jan 05 '23 10:01

rlee923


1 Answers

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", "[email protected]"),
                        new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "live.com#[email protected]")
                    })
                );

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.

like image 144
Hung Cao Avatar answered Jan 27 '23 20:01

Hung Cao