views:

130

answers:

3

Hi,

While looking at the unit tests that come with the standard ASP.MVC Web Project template, I noticed that these do not test whether or not a proper HttpVerbs attribute is set on each action method.

It's very easy to test this with reflection, but the question is whether or not it It's worth the effort. Do you check HttpVerbs in your unit test, or do you leave this up to Integration testing?

A: 

As for me I'm always checking for a proper AcceptVerbsAttribute on each action in my controllers.

eu-ge-ne
A: 

I don't but that's only because it hasn't crossed my mind until you mentioned it. I will from now on.

Andrei Rinea
oh, in this case you might find the code in my answer useful.
Adrian Grigore
+1  A: 

In case someone else finds this question: I've started checking all of my action method accept attributes in my unit tests. A bit of reflection does the trick just fine. Here's some code if you'd like to do this as well:

protected void CheckAcceptVerbs<TControllerType>(string methodName, HttpVerbs verbs)
{              
    CheckAcceptVerbs(methodName, typeof(TControllerType).GetMethod(methodName, BindingFlags.Public|BindingFlags.Instance,null,new Type[]{},null), verbs);
}

protected void CheckAcceptVerbs<TControllerType>(string methodName, Type[] ActionMethodParameterTypes, HttpVerbs verbs)
{
    CheckAcceptVerbs(methodName, typeof(TControllerType).GetMethod(methodName, BindingFlags.Public | BindingFlags.Instance, null, ActionMethodParameterTypes, null), verbs);
}

private void CheckAcceptVerbs<TControllerType>(string methodName, MethodInfo actionMethod, HttpVerbs verbs)
{
    Assert.IsNotNull(actionMethod, "Could not find action method " + methodName);
    var attribute =
        (AcceptVerbsAttribute)
        actionMethod.GetCustomAttributes(false).FirstOrDefault(
            c => c.GetType() == typeof(AcceptVerbsAttribute));


    if (attribute == null)
    {
        Assert.AreEqual(HttpVerbs.Get, verbs);
        return;
    }

    Assert.IsTrue(HttpVerbsEnumToArray(verbs).IsEqualTo(attribute.Verbs));
}

The first method is for action methods without parameters, the second is for those with parameters. You can also just use the third method directly, but I wrote the first two overloads as convenience functions.

Adrian Grigore
Great code sample :)
Andrei Rinea