Test-Driven Development with ASP.NET MVC

ASP.NET MVC has become more and more popular. In my previous post I gave you my vision about it and what it introduced to ASP.NET developers. One of the advantages of the MVC pattern is the better testability. You can easily test every controller without dealing with the View itself.

Test-Driven Development (TDD)

Principles of TDD are really simple. The entire TDD process is described on the following scheme:

Add a test

You start with creating your controllers and models. You only add methods to indicate functionality without actually implementing it. Then you add a new test. It should test this new functionality.

Let’s create a controller which allows the user to see news. We have a repository to fetch the news from and a model for news. For creating tests I am using NUnit and for mocking – my favourite framework Moq.

Run the test and see it fails

To run the test I need a test runner. I am using Visual NUnit as it is really simple and easy to integrate with Visual Studio 2010.

Write code to cover the test

OK, my test failed. Now I need to write some code so my test passes.

Run the test again and see it passes

Refactor

The final step of one TDD iteration. Usually when doing TDD you write not that good code because you are looking forward to seeing your test passes. In this step you have the chance to refactor your code so it is easy to maintain.

Conclusion

You see how easy it is to test your code when applying design patterns. MVC has many advantages and should definitely be used from developers.