Unit testing Microsoft Dynamics CRM code

If you're developing code that runs against Dynamics CRM, you know you should be testing it, right? As a developer first and foremost, I always believed that tests and documentation got in the way of the important - and more fun - stuff, but as I transitioned into a management role with responsibility for my company's Dynamics CRM system, I began to appreciate the value of the less-fun stuff.In this post I'll give you an overview of our continuous integration environment and offer a conceptual example of how to unit test your CRM code without having to execute tests against a running CRM system.Our full build and unit testing process used the following:

  1. NAnt for builds

  2. NUnit for unit tests

  3. Subversion (SVN) for version control

  4. CruiseControl.NET (CC.NET) for continuous integration

  5. Rhino.Mocks for mock object framework

Whenever a developer made a commit to SVN, CC.NET would execute the correct NAnt build target (different ones for production, testing, etc.), then it would run the NUnit tests. The results of the build (broken/successful) and the results of the NUnit tests were all reported through the CC.NET web interface so you could see a historical view. CC.NET also has a desktop notification app that is green when all builds are good or red when all builds are bad that you can use to easily check up on your development team.

Originally our NUnit tests ran against our CRM staging server and staging database, but we found that it was a problem keeping the staging system populated with "real" data, and our staging system was underpowered, so unit tests took a long time to execute. We solved this by using Rhino.Mocks to setup a mock CRM framework to verify that our code would send the correct calls to CRM without actually having to make the calls against an actual system.

Here's a conceptual example from version 4, but it will work similarly in 2011. Let's say we want to test code that deactivates an account. First, the test method sets up a mock object to represent the CRM service. Second, we set up an object to retrieve the setstate request object that the production code will pass to CRM. Third, the test method runs the production code against the mocked CRM service and captures the request object. Finally, we test the properties of the request object using an Assert.AreEqual call.

If you're ready to dig into the technical details of Rhino.Mocks + CRM, take a look at this excellent blog post with code samples: http://www.develop1.net/public/post/Unit-Testing-Dynamics-CRM2011-Pipeline-Plugins-using-Rhino-Mocks.aspx.