Unit Test for a View Attribute using Moq

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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

Method 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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x