Created
December 7, 2017 06:51
-
-
Save thojaw/4c585c4a528e30e9ddc0a2edc3b74367 to your computer and use it in GitHub Desktop.
MVC Reflection based checking of attributes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Put this in a unit test | |
var query = Assembly.Load("MyMVCProjectAssemblyName") | |
.GetTypes() | |
.Where(x => x.Name.EndsWith("Controller")) | |
.Where(x => !x.IsAbstract) | |
.Select(x => new | |
{ | |
Name = x.Name.Substring(0, x.Name.Length - 10), | |
Type = x, | |
Namespace = x.Namespace, | |
RouteAttribute = x.GetCustomAttribute<RoutePrefixAttribute>() | |
}) | |
.ToList(); | |
// Now you can perform different tests on the results, | |
// e.g. you could ensure that each Controller is decorated with Attribute | |
Assert.IsTrue(query.All(x => RouteAttribute != null)); | |
// Or you could try to validate Route Attribute against Namespace | |
Assert.IsTrue(query.All(x => x.Namespace.Contains($".{x.RouteAttribute.Prefix}."))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment