What is the best way to unit test the controller action HttpAcceptAttribute verbs?
So far I have the following but it's so ugly even a mother couldn't love it and not very flexible. Is there a better way?
[Fact] // using xUnit, mocking controller in class
public void FilterControllerTestRemoveFilterByProductAttributeIsOfTypePost()
{
Type[] paramTypes = new[] { typeof(int) };
var method = typeof(FilterController).GetMethod("MyMethod", paramTypes);
var attributes = method.GetCustomAttributes(typeof(AcceptVerbsAttribute), false).Cast<AcceptVerbsAttribute>().SingleOrDefault();
Assert.NotNull(attributes);
Assert.Equal(1, attributes.Verbs.Count());
Assert.True(attributes.Verbs.First().Equals(HttpVerbs.Post.ToString(), StringComparison.InvariantCultureIgnoreCase));
}
Thanks Mac
No reflection and magic strings, easy to rename controller and method without breaking the unit test:
[TestMethod]
public void HomeController_Index_Action_Should_Accept_Post_Verb_Only()
{
Expression<Action<HomeController>> expression = (HomeController c) => c.Index(null);
var methodCall = expression.Body as MethodCallExpression;
var acceptVerbs = (AcceptVerbsAttribute[])methodCall.Method.GetCustomAttributes(typeof(AcceptVerbsAttribute), false);
acceptVerbs.ShouldNotBeNull("");
acceptVerbs.Length.ShouldBe(1);
acceptVerbs[0].Verbs.First().ShouldBe("POST");
}