Unit Test for a View Attribute using Moq

一世执手 提交于 2019-12-01 03:13:36

问题


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");
}

回答1:


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);



回答2:


When executing the test above the AuthorizeAttribute will not be taken into account (that is, no one will evaluate it). This is normally the responsibility of the ControllerActionInvoker (a class in System.Web.Mvc).

You might want to just trust that AuthorizeAttribute is correctly implemented. Then just use reflection to verify that the AuthorizeAttribute has been correctly defined on your action.



来源:https://stackoverflow.com/questions/2296930/unit-test-for-a-view-attribute-using-moq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!