Freigeben über


SharePoint Visual Studio Unit Tests and Code Coverage

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: https://channel9.msdn.com/Blogs/adebruyn/Visual-Studio-SP1-and-SharePoint-2010-Unit-Test

Summary of steps:

  1. Install Visual Studio 2010 Service Pack 1. You can only write Unit Tests for SharePoint in VS after installing SP1
  2. Create a new C# unit test project
  3. In Project Properties change Application ->Target Framework to 3.5 and Build -> Platform Target to x64
  4. In Test - Edit Test Settings - local testsettings - Hosts tab : change run tests setting to "Run in 64 bit process on 64 bit machine"

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: https://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 https://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

  • Instrument the dll's containing code to be tested and for code coverage has to be calculated. You will have to re-sign your assembly if original assembly is signed
 VSInstr.exe "AssemlbyFile.dll" /coverage
  • Start the VSPerfCmd tool to start logging the coverage
 vsperfcmd /start:coverage /output=Custoomfileforcoverage.codecoverage
  •  Run the automated tests using MSTest utility
 mstest /testcontainer:UnitTests.dll
  • Stop logging coverage
 vsperfcmd /shutdown

Now you can open this coverage file in VS and analyze the code coverage results.

Happy Coding !