Attribute in base controller does not run in unit tests in mvc5

I understand that this is not the correct way to unit test, but we have an ActionFilterAttribute on our base controller, which never starts during our unit tests. I know that we must test it ourselves, but we want to integrate it into our full testing to the end.

[ThemeModel] public class BaseController : Controller { public MyModel Context { get; set; } } 

How do I integrate my attribute when we run a test on an inherited controller? I understand that attributes are not related to the controller and part of the mvc structure.

thanks...

+5
source share
3 answers

Two options that I think. 1 is what you are doing already, and I would not change it. 2 - the answer to your problem. I find it good to have both.

  • Keep your unit tests for the controller and filters separate. This is correct for UT, since your controller and filters should not have hard dependencies on each other. Thus, you will know that each one works correctly on its own (the principle of shared responsibility).
  • Create a separate test suite that implements HttpContextBase . I assume that you already have a mock HttpContextBase to make sessions or cookies, so I just highlighted the main points for your specific filter. (If you don't, just do a search for HttpContextBase and unit testing).

    public class MockHttpContext : HttpContextBase { public MockHttpContext() { MockRequest = new Mock<HttpRequestBase>(); // .. etc .. var actionExecutingContext = new Mock<ActionExecutingContext>(); actionExecutingContext.SetupGet(x => x.HttpContext).Returns(this); var filter = new ThemeModelAttribute(); filter.OnActionExecuting(actionExecutingContext.Object); // OnActionExecuted has similar setup if needed. } }

NTN!

0
source

Make sure the ThemeModel attribute has AttributeUsage(Inherited = true)

0
source

You must check your filter separately. Creating the necessary context objects for the controller and user. Filter.OnActionExecuted (actionExecutedContext.Object); "as syntax.

-1
source

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


All Articles