Reputation: 13
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
Upvotes: 1
Views: 441
Reputation: 427
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);
Upvotes: 1