June 21, 2012

VS2010: UnitTests targeting 3.5 and 4.0

VS2010 with SP1 installed allows running unit tests targeting .NET 3.5. But I had some issues with this and I'd like to share some tips.
First of all make sure you have read MSDN article How to: Configure Unit Tests to Target .NET Framework 3.5.

For running unit tests targeting .NET 3.5 you'll need Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version= And for running unit tests targeting .NET 4.0 you'll need Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=

When you're switching target platform in a unit test project VS actually changes reference to appropriate version of Microsoft.VisualStudio.QualityTools.UnitTestFramework. It's a subtle thing. If you changed target platform manually (in csproj) you'll have runtime errors during tests execution. One of them: "Method XXX.YYY.MyClassInitialize has wrong signature. Parameter 1 should be of type Microsoft.VisualStudio.TestTools.UnitTesting.TestContext."

If you running tests targeting 3.5 on Windows Server 2003/XP then make sure you have the following hotfix installed: http://support.microsoft.com/kb/983583/en-us. Without that hotfix I had the following error during running tests:
Object of type 'System.Runtime.Serialization.TypeLoadExceptionHolder' cannot be converted to type 'System.Collections.Generic.Dictionary`2[System.Uri,Microsoft.VisualStudio.TestTools.Common.AgentRuleDataCollector]'

I tried to create a test project which would contain tests for both platforms (3.5 and 4.0). But unfortunately I didn't manage to compose correct csproj-file. I tried to add to conditional references:

But VS2010 can't load such project file (it tries to load then silently unload without providing any error).
But with for MSBuild it's a correct project file. I successfully built it for both platforms and executed tests on them.

So I'm looking for a solution to keep and running tests targeting both 3.5 and 4.0 in a single project.