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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public interface INewsRepository { News GetNewsDetails(int newsId); ... } public class NewsController : Controller { private INewsRepository repository; public NewsController(INewsRepository repository) { this.repository = repository; } public ActionResult Details(int newsId) { return null; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
[TestFixture] public class NewsTests { [Test] public void Details_Should_Fetch_News_Details() { var repositoryStub = new Mock<INewsRepository>(); var controller = new NewsController(repositoryStub.Object); var news = new News { NewsID = 1, Title = "Test", Content = "content", PublishedOn = DateTime.Now }; repositoryStub.Setup<News>(r => r.GetNewsDetails(news.NewsID)).Returns(news); var result = controller.Details(news.NewsID); Assert.IsInstanceOf<ViewResult>(result); var view = result as ViewResult; Assert.AreEqual(view.ViewData.Model, news); } } |
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.
1 2 3 4 5 6 |
public ActionResult Details(int newsId) { var news = this.repository.GetNewsDetails(newsId); return View(news); } |
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.