I have just started to learn ASP.NET MVC. When comparing ASP.NET MVC with Web Forms one of the main advantage of MVC is always told to be better support of Unit Testing. Can I got a good explanation of how it has better support?
Edit : If possible please provide example in both.
More Control-The ASP.NET MVC framework provides more control over the HTML , JavaScript and CSS than the traditional Web Forms. Testability-ASP.NET MVC framework provides better testability of the Web Application and good support for the test driven development too.
The ASP.NET MVC Framework makes it easy and natural to unit test application functionality. It also enables a Test Driven Development (TDD) workflow that enables test-first based development.
Show activity on this post. My completely unscientific opinion: Yes; ASP.NET MVC is faster than web forms. ASP.NET MVC gives screen pops on the order of 1 to 2 seconds. Web forms is more like 3 to 5 seconds.
Asp.Net MVC has better unit testing support for one main reason - the whole architecture is built to use HttpContextBase
, HttpRequestBase
and HttpResponseBase
.
Asp.Net webforms is dependent on HttpContext.Current
, which is a singleton that you have no control over - it is set up and passed to your pages as part of the HttpApplication
executing the request. In most cases, in order to get the page to execute correctly, you need to execute it in a real HttpContext
. Since many of the properties of HttpContext are not settable (like Request and Response), it is extremely difficult to construct fake requests to send to your page objects.
This makes unit testing webforms pages a nightmare, since it couples all your tests to needing all kinds of context setup.
Contrast that to ASP.Net MVC, where you can mock an HttpContext! Now your code doesn't even need a web server to give it context, you can just set up the bits you need, and hand the mocked context to your method.
The ASP.NET page lifecycle makes it incredibly difficult to unit test classes that derive from Page
, which starts out with too many responsibilities and becomes a god object when you add application logic to it. Even worse, it has hidden dependencies on static classes and requires a default parameterless constructor, which limits your ability to inject dependencies.
So, to make an ASP.NET WebForms page testable, you need to take all the logic out of your code-behinds and put it in another class - typically a Presenter as in the Model-View-Presenter pattern.
ASP.NET MVC controllers are already separated from their templates and aren't encumbered by the ASP.NET page lifecycle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With