How to unit-test extension methods in C#

Click for: original source

A good coding practice is to keep the view layer in an MVC structure as simple as possible and with no or minimal logic. A common practice to extract common logic that you might want to use in many places is to create an extension method that could be used across views. This moves to logic from the views into a C#-based method. By Linus Ekström.

The article discusses:

  • An example of a non testable implentation
  • Refactoring the code to allow for better testability
  • Applying unit testing

With a rather simple refactoring we are now able to create unit tests and if wanted also applying TDD style coding for your extension methods. Another positive side effect of this is that you also get a better visability of the dependencies by lifting them out from the method that holds the actual implementation. Though the unit test class contains a bit of set up for the first test - adding new tests is really quick once this is done. Good read!

[Read More]

Tags programming tdd app-development