Integration Testing Your ASP.NET MVC Application
ASP.NET, Agile, MVC, Testing June 11th, 2009Let’s start with a quick recap:
- Unit tests test individual software components. They supply mocks or fake versions of dependencies (such as a database) so that the unit test doesn’t rely on any external code and any failures can be pinpointed exactly. Unit testing is central to Test Driven Development – the entire TDD process is driven by unit testing.
- Integration tests test your entire software stack working together. These tests don’t mock or fake anything (they use the real database, and real network connections) and are good at spotting if your unit-tested components aren’t working together as you expected. In general, it’s best to put most of your effort into building a solid suite of unit tests, and then adding a few integration tests for each major feature so you can detect any catastrophic incompatibilities or configuration errors before your customers do.
ASP.NET MVC famously has great support for unit testing. That’s well covered elsewhere on the web, so I won’t write more about it here. But what about integration testing?
Typically, ASP.NET MVC developers have written integration tests using a browser automation tool, such as Selenium or Microsoft’s Lightweight Test Automation Framework. These tools host a real web browser and automate a series of navigation steps, clicking on buttons and letting you write assertions about what should appear on the screen. Browser automation is fully capable of testing your JavaScript code just as easily as your business logic. However, there are also some drawbacks to browser automation:
- Browser automation test scripts are very fragile. As soon as you alter the HTML in your views, the tests may start failing and sometimes all need to be re-recorded. Many developers are happy with browser automation at first, but after a few months are sick of re-recording the tests or maintaining thousands of lines of scripts, and give up on it.
- Browser automation test scripts rely on parsing the generated HTML, which loses all the strongly-typed goodness of your MVC model objects.
So, how can we do integration testing without browser automation?
Introducing MvcIntegrationTestFramework
What if you could write NUnit tests (or xUnit or whatever you prefer) that directly submit a URL, query string, cookies, request headers, etc., into your application – without needing the app to be hosted in any web server but still running in the real (non-mocked) ASP.NET runtime – and get back the response text to make assertions about? In fact, what if you also got back the ActionResult (e.g., a ViewResult) that was executed, a reference to any unhandled exception it threw, and could also write assertions about cookie values or the contents of Session? What if you could string together a series of test requests to simulate a user’s browsing session, checking that a whole feature area works from end to end?
Well, my friend, all this can be yours with MvcIntegrationTestFramework
Download the demo project. To run the integration tests, you’ll need to install NUnit or some other test runner.
A Simple Integration Test Example
Consider the following action method:
public ActionResult Index() { ViewData["Message"] = "Welcome to ASP.NET MVC!"; return View(); }
You can write an integration for this using MvcIntegrationTestFramework as follows:
[Test] public void Root_Url_Renders_Index_View() { appHost.SimulateBrowsingSession(browsingSession => { // Request the root URL RequestResult result = browsingSession.ProcessRequest("/"); // You can make assertions about the ActionResult... var viewResult = (ViewResult) result.ActionExecutedContext.Result; Assert.AreEqual("Index", viewResult.ViewName); Assert.AreEqual("Welcome to ASP.NET MVC!", viewResult.ViewData["Message"]); // ... or you can make assertions about the rendered HTML Assert.IsTrue(result.ResponseText.Contains("<!DOCTYPE html")); }); }
This is pretty similar to a typical unit test for that action method, except that you also get access to the finished rendered HTML, in case that interests you. Unlike a unit test, this integration test goes through the entire request-processing pipeline, so it tests your routing configuration, your controller factory, any dependencies your controller has, and even your view template.
Note: That doesn’t make it better than a unit test: it just solves a different problem. Unit tests are better for driving the TDD process and for proving the correctness of individual components in isolation, and they tend to be easier to maintain large volumes of over time. Integration tests, on the other hand, are good in small doses: they cover things that unit tests cannot (such as views, database connectivity, etc.) but aren’t so fine-grained as unit tests.
Integration Tests Cover End-to-end Scenarios
Consider the following sequence of behaviours:
1. When a logged-out user visits /Home/SecretAction, they should be redirected to the login screen
2. If the user then enters a valid username and password, they should be redirected back to /Home/SecretAction
3. Since the user is now logged in, they should be shown some secret information
That’s a lot of interaction between action methods, Forms Authentication, HTTP redirections, cookies, and filters. You wouldn’t typically cover that interaction in any unit test, because each of those components is a separate unit. However, if you have an end-to-end unit test that runs through the whole process, you can feel very confident that you haven’t unintentionally broken anything (e.g., by editing web.config).
Here’s a example end-to-end integration test for this whole sequence of behaviours:
[Test] public void LogInProcess() { string securedActionUrl = "/home/SecretAction"; appHost.SimulateBrowsingSession(browsingSession => { // First try to request a secured page without being logged in RequestResult initialRequestResult = browsingSession.ProcessRequest(securedActionUrl); string loginRedirectUrl = initialRequestResult.Response.RedirectLocation; Assert.IsTrue(loginRedirectUrl.StartsWith("/Account/LogOn"), "Didn't redirect to logon page"); // Now follow redirection to logon page string loginFormResponseText = browsingSession.ProcessRequest(loginRedirectUrl).ResponseText; string suppliedAntiForgeryToken = MvcUtils.ExtractAntiForgeryToken(loginFormResponseText); // Now post the login form, including the verification token RequestResult loginResult = browsingSession.ProcessRequest(loginRedirectUrl, HttpVerbs.Post, new NameValueCollection { { "username", "steve" }, { "password", "secret" }, { "__RequestVerificationToken", suppliedAntiForgeryToken } }); string afterLoginRedirectUrl = loginResult.Response.RedirectLocation; Assert.AreEqual(securedActionUrl, afterLoginRedirectUrl, "Didn't redirect back to SecretAction"); // Check that we can now follow the redirection back to the protected action, and are let in RequestResult afterLoginResult = browsingSession.ProcessRequest(securedActionUrl); Assert.AreEqual("Hello, you're logged in as steve", afterLoginResult.ResponseText); }); }
In this test, multiple requests are made as part of the same browsing session. The integration testing framework will preserve cookies (and therefore session state) from one request to the next, so you can test interaction with things like Forms Authentication and ASP.NET MVC’s AntiForgeryToken helpers. You can see this whole thing working by downloading the demo project.
This has advantages over browser automation in that (in my opinion) it’s easier to write this test – it’s concise, you don’t need to learn a browser scripting language, and you don’t need to rerecord the script if you restructure the HTML. You can make assertions at the HTML level, or you can make assertions at the ActionResult level, with fully strongly-typed access to any ViewData or Model values that were being supplied.
On the flip side, browser automation is still the only way to test your JavaScript.
Integration Testing Your Own ASP.NET MVC Application
To add these kinds of tests to your own ASP.NET MVC application, create a new class library project called MyApp.IntegrationTests or similar. Add a reference to MvcIntegrationTestFramework.dll, which you can get by downloading the demo project and compiling it, and also add a reference to your chosen unit testing framework (e.g., NUnit or xUnit).
Next, if you’re using NUnit, create a basic test fixture class as follows:
using MvcIntegrationTestFramework.Hosting; using MvcIntegrationTestFramework.Browsing; [TestFixture] public class MyIntegrationTests { // Amend this path to point to whatever folder contains your ASP.NET MVC application // (i.e., the folder that contains your app's main web.config file) private static readonly string mvcAppPath = Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory + "\\..\\..\\..\\MyMvcApplication"); private readonly AppHost appHost = new AppHost(mvcAppPath); }
(If you’re using something other than NUnit, amend the syntax accordingly.)
Also – and seriously you can’t skip this step – you must add a post-build step so that each time you compile, Visual Studio will copy the assemblies from your integration test project’s \bin folder into your main ASP.NET MVC application’s \bin folder. I’ll explain why this is necessary later.
The test fixture you just created tells MvcIntegrationTestFramework to find your ASP.NET MVC application at the specified disk location, and to host it (without using IIS or any other web server). The resulting AppHost object then provides an API for issuing requests to your application, so you could write a test as follows:
[TestFixture] public class MyIntegrationTests { // Leave rest as before [Test] public void HomeIndex_DemoTests() { appHost.SimulateBrowsingSession(browsingSession => { RequestResult result = browsingSession.ProcessRequest("home/index"); // Routing config should match "home" controller Assert.AreEqual("home", result.ActionExecutedContext.RouteData.Values["controller"]); // Should have rendered the "index" view ActionResult actionResult = result.ActionExecutedContext.Result; Assert.IsInstanceOf(typeof(ViewResult), actionResult); Assert.AreEqual("index", ((ViewResult)actionResult).ViewName); // App should not have had an unhandled exception Assert.IsNull(result.ResultExecutedContext.Exception); }); } }
The browsingSession object lets you read and write cookies and ASP.NET session values (note: ASP.NET initializes the Session collection only after the first request in any given browsing session). The RequestResult object that comes back from ProcessRequest() lets you access the rendered response text, the actual HttpResponse object, plus the MVC ActionExecutedContext and RequestExecutedContext objects that specify what the application did in ASP.NET MVC terms.
How Does it Work Internally?
Note: if you just want to use MvcIntegrationTestFramework, you don’t need to know any of the following. I provide this info just for your interest, and to give you a head start if you want to expand the framework or change it in any way.
MvcIntegrationTestFramework uses .NET’s built-in API for creating an ASP.NET-enabled .NET appdomain and using it to host an ASP.NET application from an arbitrary disk location. The test framework then does a bunch of funky reflection-assisted stuff to attach some interceptors and event handlers to the new HTTP runtime.
When you call ProcessRequest(), internally it calls ASP.NET’s HttpRuntime.ProcessRequest() method, which invokes the request-processing pipeline. The testing framework simulates an incoming HttpWorkerRequest according to the URL, HTTP method, querystring, form values, cookies, and headers that you specify.
While the request is running, MvcIntegrationTestFramework uses its knowledge of ASP.NET MVC to add interceptors to key points in the MVC request-processing pipeline. This is how it’s able to grab and expose the ActionResult and other MVC context objects so you can make assertions about them.
Of course, all this request processing has to happen within the ASP.NET-enabled appdomain, *not* the appdomain your test runner invokes the unit test on. So, we use the slightly bizarre appHost.SimulateBrowsingSession(browsingSession => { /* your code goes here */ } syntax to shuttle your test code across the appdomain boundary and run it there. Consequently, any variables you declare outside your anonymous delegate and then use inside it *must* be serializable, or you’ll get a serialization error when they get marshalled across the appdomain boundary. This is unlikely to be a problem in real world use.
Since your test code runs in the ASP.NET-enabled appdomain, the CLR’s assembly loader will need to load your test code assembly from a location accessible to your ASP.NET MVC application. That’s why it’s necessary to have a post-build event to copy your test code assembly (and any other assemblies it references) into your ASP.NET MVC app’s \bin folder. Or you could register your test assembly in the GAC I suppose, but that’s much more hassle.
Conclusion
Personally, I find this approach to integration testing more productive than browser automation in most cases, because the tests are fast to write and are less prone to break because of trivial HTML changes. I wouldn’t want to have thousands of integration tests, though – for one thing, they’d take ages to run – but end-to-end testing for key scenarios like logging in, registering, going through shopping carts, etc., proves pretty convincingly that the major functional areas of your app are working overall, leaving unit tests to prove the fine detail of each component.
Some of the code in MvcIntegrationTestFramework was adapted from Chot’s CodeProject article, some of the ideas came from a discussion at DDD South West with Richard Fennell who’s already doing something similar except with a dependency on TypeMock, and some bits of my HttpWorkerRequest simulation code were demonstrated years ago by Phil Haack in his HttpSimulator code, which is similar to MvcIntegrationTestFramework except it predates ASP.NET MVC.
Download the demo project. To run the integration tests, you’ll need to install NUnit or some other test runner.


June 12th, 2009 at 12:51 am
Very interesting approach. Do you have plans to give the project a home?
June 12th, 2009 at 4:30 am
Interesting approach. I was recently assigned to create a web testing framework for a Webforms app. I quickly decided that recorded tests would be far too fragile — for the very reasons that you mention. Instead we built up an abstraction of the UI such that an the ID of any one HTML element is never represented in more than one place. A simple change to a UI element still breaks a lot of tests, but the fix is made in only one place. This kills a good deal of the pain of web testing, but certainly not all of it.
Here’s an idea. A while ago I had a need to make precise assertions about blocks of HTML without knowing all the details about it. I did not want to know, and I did not care, for example, that the class attribute of a certain input tag came before or after the type attribute. Likewise, a user of MvcIntegrationTestFramework might want to know that an input tag with a certain value exists without caring where it is found in the document. Doing this type of assertion will become very painful very fast using simple string manipulation.
Instead consider using an HTML parser and abstracting assertions behind extension methods. Here’s an example:
http://code.google.com/p/mvccontrib/source/browse/trunk/src/MVCContrib.UnitTests/FluentHtml/Helpers/TestExtensions.cs
This example deals with small HTML blocks as opposed to a whole document. However it’s not very hard to see how this approach might be adapted to MvcIntegrationTestFramework.
June 12th, 2009 at 7:25 am
My head spins, but I think this is awesome! Indeed, the scenario where you want to test redirects after logging in, or maybe uploads and stuff like that, could really use this integrated approach.
So how is the performance? Probably, like database integration tests, you will want to run these separately and less often?
June 12th, 2009 at 7:33 am
PS. Someone give this man an MVP!
June 12th, 2009 at 8:19 am
Interesting read!
I don’t think there’s a drawback to using Selenium. The key issue with Selenium tests is to not write any until the HTML is finished and stable. If you create your integration tests late in a project they will be of great use. I think I’d actually prefer Selenium over your approach since I would know the entire application has been tested top to bottom.
June 12th, 2009 at 9:34 am
[…] Integration Testing Your ASP.NET MVC Application - Steve Sanderson explores ways of performing integration testing on your ASP.NET MVC applications using the MvcIntegrationTestFramework […]
June 12th, 2009 at 11:39 am
[…] Integration Testing Your ASP.NET MVC Application « Steve Sanderson’s blog […]
June 12th, 2009 at 3:35 pm
For whatever reason ActionExecutedContext and ResultExecutedContext are always null in my test.
June 12th, 2009 at 5:36 pm
@Eric - no particular plans - if you want to take care of it then please feel free!
@Tim - you’re certainly right that you could perform assertions about the rendered HTML, but one of the key benefits available when testing an ASP.NET MVC app is that you can instead make strongly-typed assertions about your ViewData/Model. This eliminates much of the HTML parsing requirement.
@Mike - this integration testing framework doesn’t add any noticeable overhead, so your tests will run as fast as your MVC app can process the requests.
@Mats - Selenium tests (or any browser automation tests) certainly do provide even more coverage - they cover your JavaScript and your webserver in addition to your app. If Selenium is working well for you then that’s great. My personal experience has been that browser automation tests become unmaintainable over time, but I guess it depends on how much you need to change your views.
@Alex - not sure why that would be. Does the sample project work for you? Any idea how your app differs from a standard ASP.NET MVC application to prevent the interceptors from working?
June 12th, 2009 at 6:14 pm
I second the motion Steve Sanderson for MVP! Great post Steve.
Roberto.-
June 12th, 2009 at 7:21 pm
@Steve
It was all my fault. I was trying this under VS 2010, ASP.NET MVC 1.1 and din’t change all assembly references as needed. It works fine now and without any changes.
June 14th, 2009 at 1:53 pm
Have you thought of integrating this with Fitnesse? Could be a killer combo…
June 14th, 2009 at 9:03 pm
I’ve developed a framework for in-process WebForms testing based on exactly the same principles. It’s called Ivonna (http://sm-art.biz/Ivonna.aspx). The only difference is, WebForms are much less open for extension than the MVC framework, so I had to hack the runtime using TypeMock.
TypeMock can provide “partial integration”: e.g., you might want to run your tests against SQLite rather than MS SQL, you you can mock your database and test the integration of your view and business layer. Also, it could save some effort, e.g., you can visit a protected page without logging in.
One problem I have is a poor performance of the very first request. I guess it’s because of the site precompilation. Have you had any problems like that?
June 15th, 2009 at 4:16 am
LOL dude! I separately came up with the same exact thing for a project I’m working on - even down to the lambda stuff for crossing app domains. Great minds…
June 15th, 2009 at 3:51 pm
I am currently working on a UAT/UI testing framework (not really a framework, more combining a few other libraries) integrating selenium RC and MvcContrib.FluentHtml.
Basically im abstracting away all of the selenium calls, and using an expression based system to tie into the view model of the page under test. These expressions tie into FluentHTML making the tests and forms fully refactorable via the view model.
Ninja
June 15th, 2009 at 7:30 pm
Steve,
I’m looking forward to give this a shot.
The approach really seems more fluent and productive than browser automation.
BTW, congrats for xVal, I really appreciate it.
June 16th, 2009 at 7:41 am
@Mike Scott - I haven’t tried integrating this with Fitnesse. Although I’ve heard of Fitnesse and roughly what it does, I’ve never tried using it! If you happen to try integrating these, please let me know how it goes!
@Ulu - I came across your Ivonna framework via http://blogs.blackmarble.co.uk/blogs/rfennell and considered using it, but unfortunately needed to avoid the dependency on TypeMock. Just like yours, my integration testing framework also takes a few seconds longer to run the first test in any given batch. This is similar to how the first request to any ASP.NET application takes a few seconds to get started, so I guess it’s a fundamental fact about how ASP.NET hosting works.
@Andrew Peters - it’s reassuring to hear I didn’t miss some obvious way to bypass the cross-app-domain issues!
@Dave the Ninja - cool!
@Rafael - great, let me know how it goes. I’m most interested in whether this approach remains maintainable after writing several months worth of tests on a large project subject to frequent change, because that’s exactly the scenario I found to start getting impractical with Selenium (even though it seemed fine at first).
June 18th, 2009 at 2:21 am
Is it a good idea to embed an entire integration test inside a transaction?
I mean, is the integration test obey to the same principles than unit test?
June 18th, 2009 at 8:46 pm
@labilbe - I’m not sure what transaction you’re talking about - there aren’t any transactions in this code.
In general, integration tests don’t follow the same design principles as unit tests. For example, unit tests are supposed to test a single unit of code, decoupling it from the rest of your app, whereas integration tests don’t do any decoupling - they test the whole software stack working together.
June 19th, 2009 at 1:28 am
Sorry for my english
I will try to be more concise.
When I test my data, i embed it inside a transaction (which I rollback at the end of the test).
So I am sure my data remains the same before and after the tests.
This allows this to run tests over and over without having to rely on a specific order neither a number of times.
So my idea here is to launch an integration test which at the end does not modify anything inside my database so I can repeat it any number of times.
Is it clearer now?
Thank you.
June 19th, 2009 at 7:41 am
@labilbe - aha, I see! Thanks for clarifying. Yes, I agree that that’s a good idea. If your integration tests involve modifying a database or other persistent storage, you basically have two options:
(1) Write some code that, before each test runs, sets up some known test data in the DB. For example, to test that a banned user can’t log in, you might create a new randomly-named banned user on the fly before running that test.
-or-
(2) Set up the initial conditions manually, and then keep them stable by running your tests inside transactions that you always roll back after the test run.
Either way, it requires more work than writing a unit test, which is another reason to focus more on unit tests than integration tests. However, if you can get at least one working integration test per major feature in your app, you’ll be very well placed to detect any major config or incompatibility problems as part of your release cycle.
July 2nd, 2009 at 3:45 pm
I’d like to suggest that you copy not only the .dlls, but also the .pdbs, otherwise the stacktraces can get a bit cryptic without line information. I just spent quite a bit of time figuring that out, sadly.
August 25th, 2009 at 8:49 pm
I built something similar a while back (though not for integration testing) and I have a suggestion for you :). Rather than coping everything in a post process step, I wired up to the AppDomain.AssemblyResolve event. This event gets raised whenever an Assembly cannot be resolved. In my handler for AppDomain.AssemblyResolve I raise an event that crosses the AppDomain boundary back to the original AppDomain and requests the full path the the needed assembly. Once I have returned the full path to the needed assembly to the new Asp.Net AppDomain, I use Assembly.LoadFile(assemblyPath) to load the assembly.
This has worked really well for me. Hopfully it can help make your framework even that much easier to use.
August 25th, 2009 at 9:05 pm
@herbrandson - great idea! In fact, since I wrote this post, I’ve expanded and improved the underlying framework in numerous ways, including loading assemblies via an AssemblyResolve callback in almost exactly the way you describe.
September 1st, 2009 at 11:34 pm
What about the cassini approach?
http://timescott.wordpress.com/2008/12/09/running-integration-tests-using-cassini/
September 28th, 2009 at 8:34 am
Integration Testing Your ASP.NET MVC Application « Steve Sanderson’s blog…
Thank you for submitting this cool story - Trackback from Servefault.com…
October 27th, 2009 at 12:33 am
Great framework Steve, I am currently introducing it into my project and am looking at managing the assembly resolve event in a manner similar to that which you and @herbrandsom describe.
Does your solution still require you to copy the MvcIntegrationTestFramework assembly into the web app bin dir? If not could you provide a pointer toward solving this aspect of the problem?
Cheers and keep up the great work.
December 16th, 2009 at 7:05 pm
This looks very interesting and I am trying it out on my current project but one thing I cannot figure out is how to debug. Breakpoints which I set in the code do not get hit, though I am attaching to both the NUnit process and the w3p.exe process as well. Any ideas?
December 18th, 2009 at 8:57 am
Hi Ken
I’m surprised the debugger isn’t working for you. The ASP.NET appdomain is running inside the NUnit GUI process, so if you attach the debugger to that it should hit your breakpoints (assuming you’ve compiled in debug mode, of course). It certainly does work for me
January 14th, 2010 at 1:11 pm
Great stuff! Thanks for all the hard work. Now I’ll start with the easy bits.
February 4th, 2010 at 10:54 am
Hi Steve,
I liked the idea, and was looking for similar solution for testing my views, It’s really great that you have done the hard part! Thanks for it.
Now, there is another problem that I am facing, some of views in my application are dependent upon the the model object, they generate form fields using the model data(for example Edit pages). I want to mock the model object and pass it to the request processor so that it can pass to view engine and in last my views can render the required fields.
In essence I want to test that my required form fields exists in the view when its rendered and am going to use those form fields to post to another action to test the model binding is actually working as intended.
I can test under and over posting with existing solution by passing form fields manually.
Any help would be greatly appreciated.
February 4th, 2010 at 11:06 am
Continuing from last post…. I realized that I can use dependency injection to create fake/real models.
Now my question is how can I create two config files for web application one for hosting in IIS and one for hosting in testing framework?
February 6th, 2010 at 5:06 pm
Rohit, if you use the mechanism I’ve provided with this blog post, you’ll be doing an integration test that covers your whole application stack, including view rendering, model binding, and validation. I don’t think you’ll need to create fake models, and I’m not sure how you’d use dependency injection to do that anyway.
February 27th, 2010 at 1:36 pm
Excellent, but when accessing the Response.Headers I get a System.PlatformNotSupportedException “This operation requires IIS integrated pipeline mode.”
appHost.SimulateBrowsingSession(sess =>
{
RequestResult r = sess.ProcessRequest(”test”);
Assert.AreEqual(”value”, r.Response.Headers.Get(”key”));
});
How to enable this in Cassini? Testing the response headers are important for this project as the MVC application is a REST style web service.
March 9th, 2010 at 10:05 pm
[…] in-process (e.g., with WebRat) or using a cross-process mocking tool. I’ve already talked about hosting ASP.NET (MVC) apps in-process with integration tests (the starting point for this code); now I wanted to get the same benefits while hosting my app on a […]