如何使用moq模拟Controller.User
我有几个ActionMethods查询Controller.User的角色是这样的
bool isAdmin = User.IsInRole("admin");
在这种情况下方便地行事。
我开始用这样的代码对这些方法进行测试
[TestMethod]
public void HomeController_Index_Should_Return_Non_Null_ViewPage()
{
HomeController controller = new HomePostController();
ActionResult index = controller.Index();
Assert.IsNotNull(index);
}
并且该测试失败,因为Controller.User未设置。 任何想法?
您需要模拟ControllerContext,HttpContextBase和最终IPrincipal来模拟Controller上的用户属性。 使用Moq(v2)应该可以工作。
[TestMethod]
public void HomeControllerReturnsIndexViewWhenUserIsAdmin() {
var homeController = new HomeController();
var userMock = new Mock<IPrincipal>();
userMock.Expect(p => p.IsInRole("admin")).Returns(true);
var contextMock = new Mock<HttpContextBase>();
contextMock.ExpectGet(ctx => ctx.User)
.Returns(userMock.Object);
var controllerContextMock = new Mock<ControllerContext>();
controllerContextMock.ExpectGet(con => con.HttpContext)
.Returns(contextMock.Object);
homeController.ControllerContext = controllerContextMock.Object;
var result = homeController.Index();
userMock.Verify(p => p.IsInRole("admin"));
Assert.AreEqual(((ViewResult)result).ViewName, "Index");
}
测试用户不是管理员时的行为与将userMock对象上的期望值设置为返回false一样简单。
使用Moq版本3.1(和NUnit):
[Test]
public void HomeController_Index_Should_Return_Non_Null_ViewPage()
{
// Assign:
var homeController = new HomeController();
Mock<ControllerContext> controllerContextMock = new Mock<ControllerContext>();
controllerContextMock.Setup(
x => x.HttpContext.User.IsInRole(It.Is<string>(s => s.Equals("admin")))
).Returns(true);
homeController.ControllerContext = controllerContextMock.Object;
// Act:
ActionResult index = homeController.Index();
// Assert:
Assert.IsNotNull(index);
// Place other asserts here...
controllerContextMock.Verify(
x => x.HttpContext.User.IsInRole(It.Is<string>(s => s.Equals("admin"))),
Times.Exactly(1),
"Must check if user is in role 'admin'");
}
请注意,不需要为HttpContext创建模拟,Moq在设置测试时支持嵌套属性。
链接地址: http://www.djcxy.com/p/28027.html上一篇: How to mock Controller.User using moq
下一篇: How do I make a unit test to test a method that checks request headers?