Version 2: Dependency Injection and unit testing for Asp.Net
Thursday, June 04, 2009 6:52:47 AM
Today I released the 2.0.1 version, but before I explain the new features, I wanted to say a couple of words about the whole 2.* idea.
When you do "regular" unit testing, you often need to redesign your class so that the collaborators are not instantiated but rather "injected". After that, you can inject a mocked version of some collaborator via the constructor, for example.
Unfortunately, we don't have that luxury when testing Asp.Net views, be it WebForms or MVC. We usually call something like "Default.aspx", or "Products/List", leaving no opportunity for DI. So, what can we do?
If we look at desktop applications, there's always a top-level code that is responsible for all wireup. It's either the Main function, or the config file. It's not covered by the unit tests, but rather unit tests tend to "swap" it for some mockup. And while they can bypass it by just calling the lower-level classes, we can also bypass it -- using TypeMock!
Here comes the solution for Ivonna: make it possible to change the production top-level code for test counterparts. Including the web.config file, HttpModules, and the HttpApplication class. This is the main idea for the version 2.*.
Here's what we have in the version 2.0.1:
- We can modify the configuration, including, but not limited to, app settings and connection strings.
- In case this is not enough, we can swap the entire web.config file for, say, test.config. Should be in the root directory of the Web, but I think this is a temporary limitation.
- We can manipulate the HttpModules collection. Ok, actually, it's module types. This feature was implemented for the 2.0.0 and is already superceded by the writable configuration introduced in 2.0.1
- In 2.0.2, we'll be able to plug into the point at which the HttpApplication is initialized, and modify some of its properties, including the Modules collection. Note, however, that this instance will be probably alive in the tests that follow.
Download it here.
codeproject