Unit Test for a View Attribute using Moq

后端 未结 2 1241
北恋
北恋 2021-01-13 08:21

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         


        
相关标签:
2条回答
  • 2021-01-13 08:29

    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);
    
    0 讨论(0)
  • 2021-01-13 08:42

    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.

    0 讨论(0)
提交回复
热议问题