Wednesday, October 17, 2012

How to unit test a classic Web Site project (app_code)

I recently worked on a legacy system (banking) containing several old Web Site projects (needless to say they were "thick" and not backed up by any tests). As a strong believer in the value of unit tests I wanted to write isolated tests to express the business intention behind the logic as well as proving it actually worked (without the need to find test data in an environment that includes many 3rd party systems and platforms).

So what are your options when it comes to unit testing code in a classic Web Site (app_code) based project? Or first off, what is the challenge? Well, classic Web Site projects rely on run-time compilation so there's no way to just add a reference to the assembly/project under test as you normally would do. Or is it?

If you do some search on the topic you'll find various suggestions:
  • "Migrate the Web Site project to a Web Application project"
    Sure - I'd definitely opt for this solution if you can get away with it. In my case such a change would require changes to a quite complex build/deploy process as well so it was not a feasible short term solution.
  • "Move the code to be tested from the app_code folder into a separate class library"
    My new code had a lots of dependencies to existing code that lived under the app_code folder, so it  would have been a quite large change...again not feasible at this point in time. 
  • "It's not possible"
    Writing code that can't be unit tested is a personal no go, so that kept me searching for another solution...

....and here's what I ended up with: 

  1. Create your unit test project
  2. Create a precompile->output folder structure in the unit test project.

  3. Edit the unit test .csproj file and add a pre-compile step to trigger a build of the Web Site project that contains the code you'd like to unit test.
    PhysicalPath: The Web Site project you'd like to write tests against
    TargetPath: The relative path to the folder you created in step 2.

  4. If you now build your unit tests project you should see the precompile->output folder getting filled with binaries from the Web Site project.
  5. Voila - you can now go ahead and add a reference to the precompile->output->bin->App_Code.dll. Every time you re-build our solution the referenced App_Code.dll assembly will be updated as expected.

2 comments:

  1. Wow! This is exactly what I am looking for. Thanks a ton

    ReplyDelete