October 19, 2015

Better Assertions with Shouldly

Shouldly is a open source assertion library for .NET which uses extension methods to simplify the assert syntax in Unit Tests. It can help to improve the readability of test code because the tests read like humans speak. Instead of asserting that one value satisfies the criteria of another we simply yet elegantly say such and succh value "should be" X criteria.
Take a look at the following examples:

Another nice feature of Shouldly is that it can work with just about any Unit Test Framework (NUnit, XUnit, MSTest). Shouldly is easy to use and even simpler to install makes testing code much clearer.
It is available on GitHub and as a Nuget package.
For more details and advanced options please see the full Pluralsight course on the subject Better Unit Test Assertions with Shouldly.

April 2, 2015

MVC Action Filters and the Case of the Russian Dolls

MVC Action Filters are a great way to add functionality that will run on every request.

However they can be a little tricky and have some unwanted side affects when using child actions via Html.Action.

The problem is that Action Filters will run multiple times by default when called via Html.Action. Once for the original action and then another time for each of the child actions. To prevent this from happening you need to ensure that the action filter is only called for the original action and not for the subsequent child actions. You can detect this situation by checking the filterContext.IsChildAction property.

So to properly handle the situation first check if the action is a child action and if it is not then run your code as normal. If it is a child action then do not run your code. Here is a simple example: