In an earlier post, I discussed a technique I developed for manipulating the HttpContext within NUnitAsp tests. Well, one of the major impetus (impeti? impetuses? gaggle?) for this technique came from me banging my head against a wall trying to figure out how to create testing scenarios that would isolate the user interface from my business logic and/or data access.
I started out with the idea of creating a little MVC (Model-View-Controller) structure with the Model being the business domain object (or group of objects), the View being the aspx page, the code behind handling events from the View, and then creating a separate Controller that the code behind would delegate calls to as needed – primarily when it needed to interact with the business or data layer.
Something like this:

And then I thought to myself that man shall need a way to decouple the creation of the controller from the code behind so that it may be set by a test scenario. So I spake into the darkness to create a ControllerFactory, and it was created and it was good, and I saw that it was good.

But it wasn’t. Good that is.
This is where head-banging ensued (and not the Beavis & Butthead kind). When I tried to swap a mock controller into the factory using the static SetPageController method, it didn’t work. It didn’t throw an error, but the controller that the page used during the test was not the mock controller that I expected. Not cool. That’s when it hit me that the test was running in a different context from the actual page. I thought all was lost. All this for naught.
But, alas, all was not for (uh) naught. Not at all! As you already know, I discovered the workaround technique mentioned previously, so the day (and my head) was saved.
So, putting it all together using this technique and the MVC-like pattern, I was able to swap in and out my trusty mock controllers at will, allowing me to write focused tests on the user interface interactions like so:
For a more detailed and complete code sample, get the source here.