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
基础教程推荐
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- WPF 模态进度窗口 2022-01-01
