Ncrunch, SharePoint and Microsoft Fakes

For the past month I have been working with SharePoint and also neglecting to blog. Today I stop that neglect to share something about TDD and SharePoint.

I use a product call NCrunch, a wonderful test runner with a difference, it runs tests continuously. The power really shows when you practice Red Green Refactor. Just keep coding, don’t stop, make a change wait a second, see the results. To anyone who is serious about TDD I recommend you go get the trial of this tool.

The latest version of NCrunch has support for Microsoft Fakes. I won’t be going into Fakes in any detail today, I will leave that for another post, but simply it helps you mock out code that is not mockable. Not being able to mock code is the biggest road block when you write things in a TDD manner, Fakes provide a way to take control. Rather than injecting a mocked contract into the SUT (System Under Test) your tests run in a mocked context. There are two ways you can use fakes, Stubs and Shims, Stubs are just good old DI (Dependency Injection) and Shims are magic.

Shims allow you to intercept code at runtime. When arranging your tests you declare this interception, then when you’re SUT calls the dependency it is redirected to your Shim. All you need to do is add a fake assembly to your project and you can start using the framework. This is of great use when working with the SharePoint API.

When faking SharePoint in your project you will notice a very long pause as the compiler generates the faked assembly for you, this is fine if you see the pause once, however throwing NCrunch into the mix some issue start to appear. NCrunch builds a number of workspaces to run your tests, and the generation of faked assemblies is part of this build. The more workspaces you have the longer the generation takes and the longer you have to wait to see your tests pass.

There is a workaround to this, tell NCrunch to copy the pre generated faked assemblies. This is achieved by using the “Additional Files To Include” option in the NCrunch project configuration.

Select the NCrunch Configuration
NCrunch Menue

Select the Project the test project that uses the faked assemblies
NCrunch Configuration

In the General section below the projects list you will see the “Additional Files To Include” Click on the choose button
NCrunch Configuration

This screen list all the file that are already being copied to the work space for this project. Click the “Add File(s)...” button
Additional Files To Include

Navigate to the FakeAssemblies Directory
Additional Files To Include

Select all the files in that Directory click ok
Additional Files To Include

You will see the files in the files in the “Additional Files To Include” windows click OK
Additional Files To Include

Now watch your test run quickley.

Before
Before

After

After