Should I be testing attributes in an ASP MVC project?

I have a fairly common scenario on my hands that involves two action methods of the same name - one for handling POST requests and another for handling GET requests:

public ActionResult Add()
{
    return View();
}

[HttpPost]
public ActionResult Add(Question question)
{
    repository.Add(question);
    return RedirectToAction("Index");
}

      

As you can see, action methods are differentiated using an attribute. If I remove the attribute HttpPost

, the runtime hits the yellow screen of death.

My question is, is it smart to write a unit test that uses reflection to make sure that this particular method is decorated with an attribute HttpPost

? I have a tendency to do this because if someone accidentally removes this attribute, the server will crash.

+3


source to share


1 answer


Your post method already has a different C # signature, so you are at least validating it. I think this is at the discretion of the tester, but not required. Queries GET

and POST

are an integral part of the Internet.

If you choose to do this, you can do something like



var postMethod = typeof(NameOfController).GetMethods().FirstOrDefault(p => p.GetCustomAttribute<HttpPost>(false) != null && p.Name == "Add");
Assert.IsTrue(postMethod != null);

      

It cannot compile verbatim, but that is what it is. Be sure to add System.Reflection

to use extension methods.

+1


source







All Articles