简体   繁体   中英

Should I test for attributes in an ASP MVC project?

I have a pretty 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, the action methods are differentiated by means of an attribute. If I remove the HttpPost attribute, the runtime will crash with a yellow screen of death.

My question is: Is it sensible to write a unit test that uses reflection to verify that this particular method is decorated with the HttpPost attribute? I have an inclination to do so because if someone accidental removes the attribute, the server will crash.

Your post method already has a different signature in C#, so you are at least testing it exists. I think this is at the tester's discretion but not absolutely necessary. GET and POST requests are intrinsic to the Web.

If you do decide to do it, 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 may not compile verbatim but that is the gist of it. Make sure to add System.Reflection for the extension methods to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM