06 December 2016

How to Unit Test that an ASP.NET MVC Controller Only Accepts an HTTP GET


How to test that an ASP.NET MVC Controller Only Accepts an HTTP GET


Test-Driven Development (TDD)

An important agile priniciple is that code only be written in response to a test. Covering unit tests along with continuous integration (CI) allows development to move quickly and be confident that new code will not break old code.



Testing Orthogonal Concerns

The challenge with testing for HTTP Verb limitations is that, to follow the Single Responsibility Principle (SRP), the code limiting the verbs should be an orthogonal concern (i.e. that it should not be directly in the controller method).

Thankfully, ASP.NET MVC allows a developer to limit the HTTP verbs that a controller accepts via an Attribute.

How to verify that a method has an Attribute

Since ASP.NET MVC development uses managed languages, Reflection allows a test author to verify that an attribute has been applied.

Suppose one wants to test the following method for the presence of an HttpGet attribute:


The process for testing for an attribute is simple.

  1. Get a reference to the type.
  2. Get a reference to the method.
  3. Get a reference to the custom attribute.
  4. Test that the reference is not null (i.e. that the attribute was applied to the method)


Code

Below is code showing how to test for the presence of an attribute on a method.


Below is a more complicated example which tests that the attribute is configured in a certain way.




No comments: