多么嘲笑User.Identity
How mock User.Identity
我想在控制器中测试一种方法
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);
}
如何将 HttpContext 中的模拟 User.Identity.Name 添加到我的模拟控制器?
[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);
}
*更改断言
您需要在控制器上模拟 HttpContext
例如:
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);
我想在控制器中测试一种方法
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);
}
如何将 HttpContext 中的模拟 User.Identity.Name 添加到我的模拟控制器?
[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);
}
*更改断言
您需要在控制器上模拟 HttpContext
例如:
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);