Last active
December 15, 2015 01:09
-
-
Save gabrieljoelc/5178070 to your computer and use it in GitHub Desktop.
Shows how to use `ReflectedControllerDescriptor` and `ReflectedControllerDescriptor#GetCanonicalActions()` method. It also references the `NonActionAttribute` and a method that returns the default value of a specified type (`GetDefault(Type)`). It leverages of MvcContrib test helpers (i.e. `ActionResultHelper`).
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
using System; | |
using System.Linq; | |
using System.Web.Mvc; | |
using Microsoft.VisualStudio.TestTools.UnitTesting; | |
using MvcContrib.TestHelper; | |
using NSubstitute; | |
namespace My.Tests.Web.Controllers | |
{ | |
[TestClass] | |
public class MyActionDescriptorControllerTests | |
{ | |
[TestMethod] | |
public void All_controller_actions_have_fooId_as_first_parameter() | |
{ | |
ActionDescriptor[] actionDescriptors = GetAllActionMethodInfos(); | |
foreach (var actionDescriptor in actionDescriptors) | |
{ | |
var parameters = actionDescriptor.GetParameters(); | |
var personIdParamInfo = parameters.FirstOrDefault(); | |
Assert.IsNotNull(fooIdParamInfo); | |
Assert.AreEqual(typeof(Guid), fooIdParamInfo.ParameterType); | |
Assert.AreEqual("fooId", fooIdParamInfo.ParameterName); | |
} | |
} | |
[TestMethod] | |
public void When_HasBar_all_controller_actions_redirect_to_other_action() | |
{ | |
var fooId = Guid.NewGuid(); | |
IFooRespository fooRepo = Substitute.For<IFooRespository>(); | |
fooRepo.Get(personId).HasBar().Returns(true); | |
var controller = new MyActionDescriptorController(fooRepo); | |
ActionDescriptor[] actionDescriptors = GetAllActionMethodInfos(); | |
foreach (var actionDescriptor in actionDescriptors) | |
{ | |
var parameters = actionDescriptor.GetParameters() | |
.ToDictionary( | |
x => x.ParameterName, | |
x => x.ParameterName == "fooId" ? fooId : GetDefault(x.ParameterType) | |
); | |
var result = actionDescriptor.Execute(controller.ControllerContext, parameters); | |
Assert.IsNotNull(result); | |
var actionResult = result as ActionResult; | |
actionResult | |
.AssertActionRedirect() | |
.ToAction("View") | |
.ToController("FooController") | |
.WithParameter("id", fooId); | |
} | |
} | |
protected ActionDescriptor[] GetAllActionMethodInfos() | |
{ | |
return new ReflectedControllerDescriptor(typeof(MyActionDescriptorController)) | |
.GetCanonicalActions() | |
.Where(x => !x.GetCustomAttributes(typeof(NonActionAttribute), true).Any()) | |
.ToArray(); | |
} | |
static object GetDefault(Type type) | |
{ | |
return type.IsValueType ? Activator.CreateInstance(type) : null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment