Can I check the override for OnAuthorization in the base class of the ASP.NET MVC controller?

The mechanisms for doing this work are not complicated, but testing is a bit strange. The scenario is that I want to dump some basic user data into the view data based on the User property of the base controller (IPrincipal object), so that the main page always has it. I need access to my IUserManager (service class), which is provided by the custom DI in the factory controller. Mocking the user is not a problem for testing. However, the easiest way to achieve this for every action in the base controller is to do this by overriding the OnAuthorization method. Then the base class is as follows:

public abstract class BaseController : Controller
{
    public BaseController(IUserManager userManager)
    {
        UserManager = userManager;
    }

    public IUserManager UserManager { get; private set; }

    protected override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);
        UserManager.SetupUserViewData(User, ViewData);
    }
}

, , OnAuth . mock UserManager, SetupUserViewData. , ( IUserManager).

? , .

+3
1

, , , OnAuthorization. - :

public class TestController : BaseController {
    public TestController(IUserManager userManager) : base(userManager) {
    }

    public void CallOnAuthorization(AuthorizationContext filterContext) {
        OnAuthorization(filterContext);
    }
}

:

[Test]
public void TestMethod() {
    var userManager = //Mock usermanager;
    var filterContext = //Mock AuthorizationContext;
    var controller = new TestController(userManager);
    controller.CallOnAuthorization(filterContext);
    //Assert here
}
+8

Source: https://habr.com/ru/post/1733139/


All Articles