Last active
August 29, 2015 13:56
-
-
Save trailmax/9026408 to your computer and use it in GitHub Desktop.
Verify that all appropriate controller actions have a sitemap/breadcrumb attribute. Rewritten in xUnit data Attribute.
This file contains hidden or 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
// Issue with this approach is when there is nothing is wrong with the solution and no actions are in the bad, i.e. test should pass | |
// this test still fail with error saying "No data found". | |
public class ControllerActionsDataAttribute : DataAttribute | |
{ | |
public override IEnumerable<object[]> GetData(MethodInfo methodUnderTest, Type[] parameterTypes) | |
{ | |
var controllerTypes = SitemapControllersTests.GetControllerTypes(); | |
var offendingActions = controllerTypes.Where(ct => !SitemapControllersTests.ExcludedControllers.Contains(ct)) | |
.SelectMany(c => c.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) | |
.Where(m => !m.IsDefined(typeof(NonActionAttribute))) | |
.Where(m => !m.IsDefined(typeof(GeneratedCodeAttribute))) | |
.Where(m => typeof(ActionResult).IsAssignableFrom(m.ReturnType)) | |
.Where(m => !m.IsDefined(typeof(HttpPostAttribute))) | |
.Where(m => !m.IsDefined(typeof(MvcSiteMapNodeAttribute))) | |
.Where(m => !SitemapControllersTests.ExcludedReturnTypes.Contains(m.ReturnType)) | |
.Select(m => new object[]{m}); | |
return offendingActions; | |
} | |
} | |
/// <summary> | |
/// Verify that all appropriate controller actions have a sitemap/breadcrumb attribute | |
/// </summary> | |
public class SitemapControllersTests | |
{ | |
public static readonly List<Type> ExcludedControllers = new List<Type>() | |
{ | |
typeof(HelpController), | |
typeof(HomePageController), | |
}; | |
public static readonly List<Type> ExcludedReturnTypes = new List<Type>() | |
{ | |
typeof(PartialViewResult), | |
typeof(JsonResult), | |
typeof(FileResult), | |
}; | |
[Theory] | |
[ControllerActionsData] | |
public void ControllerActions_Always_HaveBreadcrumbAttributeAlternative(MethodInfo actionInfo) | |
{ | |
Assert.Null(actionInfo); | |
} | |
public static IEnumerable<Type> GetControllerTypes() | |
{ | |
return Assembly.GetAssembly(typeof(MvcApplication)) | |
.GetTypes() | |
.Where(t => !t.IsAbstract && t.IsSubclassOf(typeof(Controller))) | |
.Where(t => t.Namespace != null && !t.Name.Contains("T4MVC")) | |
.ToList(); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment