How to mock Controller.User using moq(如何使用 moq 模拟 Controller.User)
问题描述
我有几个 ActionMethods 像这样查询 Controller.User 的角色
I have a couple of ActionMethods that queries the Controller.User for its role like this
bool isAdmin = User.IsInRole("admin");
在这种情况下方便地采取行动.
acting conveniently on that condition.
我开始用这样的代码对这些方法进行测试
I'm starting to make tests for these methods with code like this
[TestMethod]
public void HomeController_Index_Should_Return_Non_Null_ViewPage()
{
HomeController controller = new HomePostController();
ActionResult index = controller.Index();
Assert.IsNotNull(index);
}
并且该测试失败,因为未设置 Controller.User.有什么想法吗?
and that Test Fails because Controller.User is not set. Any idea?
推荐答案
你需要Mock ControllerContext、HttpContextBase,最后是IPrincipal来模拟Controller上的用户属性.使用 Moq (v2) 应该可以使用以下几行.
You need to Mock the ControllerContext, HttpContextBase and finally IPrincipal to mock the user property on Controller. Using Moq (v2) something along the following lines should work.
[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 一样简单.
Testing the behaviour when the user isn't an admin is as simple as changing the expectation set on the userMock object to return false.
这篇关于如何使用 moq 模拟 Controller.User的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 moq 模拟 Controller.User


基础教程推荐
- 从 C# 控制相机设备 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 将数据集转换为列表 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 如果条件可以为空 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03