I spent almost 10 hours yesterday to figure out how to run SharePoint unit tests using VS 2010 and how to get code coverage reports. There is nothing new which I have invented in this process but I felt this information is right now scattered . I'm putting down the complete process here so that others don't struggle while implementing this.
As most of you have seen by now that Visual Studio has added capability to execute unit test cases for SharePoint 2010. The details of how it can be achieved are available in this nice video: http://channel9.msdn.com/Blogs/adebruyn/Visual-Studio-SP1-and-SharePoint-2010-Unit-Test
Summary of steps:
Making these settings changes helps us to run the 64-bit SharePoint code in unit tests created using VS 2010 SP1. Visual Studio 2010 SP1 enables the IntelliTrace debugging technology on 64-bit Microsoft SharePoint solutions.
Once you have written the unit test cases, next thing is to see how much code coverage we are getting by running these unit test cases. Enabling Data Adapters is not supported with tests that target .Net Framework 3.5 in Visual Studio. Therefore code coverage data adapter will not work from VS as SharePoint projects target .NET 3.5. Details available at VS Test team blog: http://blogs.msdn.com/b/vstsqualitytools/archive/2010/12/19/how-to-re-target-unit-tests-to-net-framework-3-5-in-vs-2010-sp1.aspx
The only solution is to run the tests and coverage from command line tools. This involves instrumenting the libraries for which code coverage has to be checked. The details of this process has been nicely documented at http://blogs.microsoft.co.il/blogs/royrose/archive/2011/08/30/manually-configure-and-run-code-coverage.aspx
I'm summarizing the steps here. Ensure you run 64 bit versions of these utilities. This is something which took me some time to figure out. These are available at <VSDir>\ Team Tools\Performance Tools \x64
VSInstr.exe "AssemlbyFile.dll" /coverage
vsperfcmd /start:coverage /output=Custoomfileforcoverage.codecoverage
mstest /testcontainer:UnitTests.dll
vsperfcmd /shutdown
Now you can open this coverage file in VS and analyze the code coverage results.
Happy Coding !