单元测试使用起订量视图属性 [英] Unit Test for a View Attribute using Moq
问题描述
我使用起订量的单元测试,我想测试一个视图的属性。
在这种情况下,授权的属性
查看示例code:
[授权(角色=UserAdmin)]
公共虚拟的ActionResult ADDUSER()
{
//这里查看逻辑
返回查看();
}
所以,我想测试视图属性时,我的行为对这个观点与在UserAdmin的角色的用户,这是不是在admin用户角色的用户。反正有做到这一点?
试验例:
[测试]
公共无效Index_IsInRole_Customer()
{
//安排
UserAdminController控制器= _controller;
rolesService.Setup(R = GT; r.IsUserInRole(It.IsAny<串GT;(),It.IsAny<串GT;()))返回(假)。 //任何作用返回false //法案
VAR的结果= controller.AddUser(); //断言
Assert.IsNotNull(结果,结果为空);
}
属性仅仅是元数据类型,所以他们没有做任何事情,除非周围的基础设施,让他们做一些事情(或更好:周围基础设施做一些事情基于在这些属性的信息)。这时候,它执行的请求ASP.NET MVC框架做了什么。
这是不是当你创建和调用在单元测试控制器动作你做了什么,所以除非你要竭尽全力来调用使用ControllerActionInvoker(此时测试不再是一个单元的控制器操作测试,成为一个集成测试),你不能直接测试的行为的由属性暗示。
您可以,但是,写一个单元测试,验证属性正确装饰控制器动作:
VAR属性= typeof运算(UserAdminController)
.GetMethod(ADDUSER)GetCustomAttributes(真)。
VAR的结果= attributes.OfType< AuthorizeAttribute>()单()。
Assert.AreEqual(UserAdmin,result.Roles);
I am using Moq for unit testing and I would like to test for a view's attribute. In this case the Authorize attribute.
Example View Code:
[Authorize(Roles = "UserAdmin")]
public virtual ActionResult AddUser()
{
// view logic here
return View();
}
So I would like to test the view attribute when I act on this view with a user that is in the role of UserAdmin and a user that is not in the role of user admin. Is there anyway to do this ?
Example Test:
[Test]
public void Index_IsInRole_Customer()
{
// Arrange
UserAdminController controller = _controller;
rolesService.Setup(r => r.IsUserInRole(It.IsAny<string>(), It.IsAny<string>())).Returns(false); // return false for any role
// Act
var result = controller.AddUser();
// Assert
Assert.IsNotNull(result, "Result is null");
}
Attributes are just metadata on the type, so they don't do anything unless the surrounding infrastructure make them do something (or better yet: the surrounding infrastructure does something based on the information in those attributes). That's what the ASP.NET MVC framework does when it executes a request.
That is not what you do when you create and invoke a Controller Action in a unit test, so unless you want to go to great lengths to invoke the Controller Action using a ControllerActionInvoker (at which point the test ceases to be a unit test and becomes an integration test) you can't directly test the behavior implied by the attribute.
You can, however, write a unit test that verifies that the attribute correctly decorates the Controller Action:
var attributes = typeof(UserAdminController)
.GetMethod("AddUser").GetCustomAttributes(true);
var result = attributes.OfType<AuthorizeAttribute>().Single();
Assert.AreEqual("UserAdmin", result.Roles);
这篇关于单元测试使用起订量视图属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!