How to create an Asp.net user ID when testing WebApi controllers

I am using Web API 2. In the web api controller, I used the GetUserId method to generate a user ID using Identity Asp.net.

I need to write an MS unit test for this controller. How can I access the user ID from a test project?

I gave an example code below.

Web api controller

 public IHttpActionResult SavePlayerLoc(IEnumerable<int> playerLocations) { int userId = RequestContext.Principal.Identity.GetUserId<int>(); bool isSavePlayerLocSaved = sample.SavePlayerLoc(userId, playerLocations); return Ok(isSavePlayerLocSaved ); } 

Web API Controller

 [TestMethod()] public void SavePlayerLocTests() { 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("admin"); var controller = new TestApiController(); var actionResult = controller.SavePlayerLoc(GetLocationList()); var response = actionResult as OkNegotiatedContentResult<IEnumerable<bool>>; Assert.IsNotNull(response); } 

I tried using the layout as described above. But that does not work. How can I generate the Asp.net user ID when calling the test method on the controller?

+5
source share
1 answer

If the request is authenticated, then the User property must be populated with the same principle.

 public IHttpActionResult SavePlayerLoc(IEnumerable<int> playerLocations) { int userId = User.Identity.GetUserId<int>(); bool isSavePlayerLocSaved = sample.SavePlayerLoc(userId, playerLocations); return Ok(isSavePlayerLocSaved ); } 

for ApiController you can set the User property while placing the unit test. However, this extension method is looking for ClaimsIdentity , so you must provide one

The test will now look like

 [TestMethod()] public void SavePlayerLocTests() { //Arrange //Create test user var username = "admin"; var userId = 2; var identity = new GenericIdentity(username, ""); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userId.ToString())); identity.AddClaim(new Claim(ClaimTypes.Name, username)); var principal = new GenericPrincipal(identity, roles: new string[] { }); var user = new ClaimsPrincipal(principal); // Set the User on the controller directly var controller = new TestApiController() { User = user }; //Act var actionResult = controller.SavePlayerLoc(GetLocationList()); var response = actionResult as OkNegotiatedContentResult<IEnumerable<bool>>; //Assert Assert.IsNotNull(response); } 
+4
source

Source: https://habr.com/ru/post/1262625/


All Articles