1

I want to testing one method in controller

public class CardController : Controller { IRepository repository; public CardController(IRepository repo) { repository = repo; } [AcceptVerbs("Get", "Post")] public IActionResult CheckPublicID(string PublicID) { if (repository.CheckCardName(PublicID, User.Identity.Name)) { return Json(true); } return Json(false); } 

How i can add mock User.Identity.Name in HttpContext to my mock controller?

[Fact] public void CheckPublicIDIsEmpty() { Mock<IRepository> mock = new Mock<IRepository>(); mock.Setup(r => r.CheckCardName("TestID", "TestName")).Returns(false); //mock User.Identity.Name CardController cardController = new CardController(mock.Object); var result = cardController.CheckPublicID("TestID"); var viewResult = Assert.IsType<JsonResult>(result); Assert.Equal(false, viewResult.Value); } 

*change Assert

1
  • User property actually refers to HttpContext - public ClaimsPrincipal User => HttpContext?.User; so you need to mock HttpContext instead. See this reply. Does it answer your question? Commented Aug 23, 2021 at 8:29

1 Answer 1

1

You need to mock the HttpContext on the controller for example :

var httpContext = new DefaultHttpContext() { User = new System.Security.Claims.ClaimsPrincipal(new GenericIdentity("username")) }; var actionContext = new ActionContext(httpContext, new Microsoft.AspNetCore.Routing.RouteData(), new Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor()); cardController.ControllerContext = new Microsoft.AspNetCore.Mvc.ControllerContext(actionContext); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.