Dipping my toes into asp.net and mvc, more specifically the web-api (2.0) part of MVC 5, I like the idea of using attributes and creating your own attribute classes to control how requests are handled and responses returned for all api end-points.
The “How to test “Only certain roles should have access to a controller in MVC” article describes how to unit test a single controller to ensure that it keeps the correct attributes and doesn’t get undesired attributes added.
That is a perfectly valid way of unit testing individual controllers. However, I prefer to have all tests of the API configuration in a single place instead of spread around unit tests of individual controllers. Especially as, using attribute routing, a controller can very easily be replaced by a different controller which may not have the correct attributes and whose test companion doesn’t test for them.
What I envision is a single test class where all aspects of the API configuration can be secured against undesired effects of (inadvertent) changes. What I am struggling with is how to set this up. Bryan Avery’s article (mentioned above) shows how to get a list of the custom attributes of a controller class, but:
how do I get my hands on a list of all controllers present in the test project?
Answer
Reflection ought to help you here:
var myControllers = Assembly.Load(yourAssemblyName) .GetTypes() .Where(t => typeof(t).IsAssignableFrom(ApiController)) .ToList();