Unit Test for Moq View Attribute

I use Moq for unit testing, and I would like to check the view attribute. In this case, the Authorize attribute.

Example:

[Authorize(Roles = "UserAdmin")]
public virtual ActionResult AddUser()
{
   // view logic here  
   return View();
}

So, I would like to test the view attribute when I work on this view with a user who is in the role of UserAdmin and a user who is not in the role of user admin. Is there any way to do this?

Test example:

[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");
}
+5
source share
2 answers

- , , - ( : - ). , ASP.NET MVC .

, , unit test, , ControllerActionInvoker ( unit test ), , .

, , unit test, , Action Controller Action:

var attributes = typeof(UserAdminController)
    .GetMethod("AddUser").GetCustomAttributes(true);
var result = attributes.OfType<AuthorizeAttribute>().Single();
Assert.AreEqual("UserAdmin", result.Roles);
+9

AuthorizeAttribute ( ). ControllerActionInvoker ( System.Web.Mvc).

, , AuthorizeAttribute . , , AuthorizeAttribute .

+1

All Articles