Tag: MVC

Perform JavaScript Validation of Date Input for ‘dd/mm/yyyy’ Format

Generally speaking, in this day and age you shouldn’t need to roll your own javascript-based date validation when using ASP.NET MVC. DataAnnotations attributes on your view model properties should allow you to define the validation criteria you need. If you then need the validation to occur client-side you can then use the jquery.validate.unobtrusive.js library in collaboration with the Globalize.js fix described here (hint: not the response marked as the answer, as that one is — quite simply — stupid).

However, sometimes you might find a weird scenario where you can’t do the above, and are looking for a nice way to parse/validate a date string into a date. In my case I was dealing with the dd/mm/yyyy format and wanted to either return the date when valid, or null when invalid. It’s slightly convoluted, but works well:


Unit Testing an ASP.NET MVC Controller

Some people argue that there is no value in testing MVC Controllers as they should not be housing any complex logic. These people would argue that, at most, MVC Controllers should be tested as part of integration testing, but shouldn’t warrant unit testing.

Obviously, if all you’re doing is integration testing then there probably isn’t much call for mocking, but I would argue that there are valid reasons for unit testing MVC Controllers…

  • Ensuring that correct view/view model is returned for each Action;
  • Ensuring that all relevant mocked domain logic components are invoked;
  • Ensuring that all expected validation errors are raised and returned in the ActionResult;
  • Ensuring that functionality sometimes implemented at Controller level (such as sorting and some elements of paging) are working as expected.

Any form of testing should always fall under the constraints of the Law of Diminishing Returns, and so we shouldn’t test MVC Controllers for the sake of it. However, if we’re smart about how we structure our tests we should have pretty good coverage with minimal test-writing required.

So with the justification out of the way — not that we needed justification, ‘cos writing tests is fun, right? (right?) — we are now faced with the problem of mocking all the dependencies we need to test a Controller. This, as you may imagine, is not simple, with all the Request contexts, Server contexts, Identity contexts, etc. Fortunately for you, I have been through the pain and have found all the things that need to be mocked and how to mock them in order to have a testable MVC Controller with all the contextual elements present and accounted for…

Note: The below example is dependent upon my ArrangeActAssert Test Class Structure.