Share via


Mocking Visual Studio

One of the really cool features (that I only briefly mentioned here a few months ago) that ships in the Visual Studio SDK is the ability to do test driven development and/or unit tests when developing a VSPackage. If you read up on TDD, one of the best practices you'll come across is the idea of doing true unit testing. That is, isolating a component (whatever you're testing) as much as possible to ensure that you are only testing the target object. You shouldn't have to worry about setting up a complex testing infrastructure just to see if a class executes in a certain fashion. This is pretty easy to accomplish if you're writing classes with very simple functionality, but this quickly becomes a challenge when you have a lot of objects talking to each other.

To overcome this hurdle, one popular approach is to use mock objects. These can be found in a variety of flavors, but the basic idea is that you create dummy objects that are just smart enough to make the code under test execute the way you want it to. The dummy objects aren't supposed to do any actual work though.

For example, let's say you're developing a Visual Studio Package in C#, and in one method, you need to write something to the Output toolwindow. Of course, to do this in your package, you would follow the basic services pattern that you use all the time in VSPackage development:

  1. Call GetService to get a Service object
  2. Cast the service to the specific interface you want to use
  3. Use the interface

This is all well and good if your package is running inside Visual Studio and has access to the various services available, but how would you accomplish this if your package dll was running inside a unit test harness like VSTS or NUnit? After all, your package wouldn't be "sited" inside Visual Studio (no IServiceProvider instance) and therefore shouldn't be able to ask for VS services.

This is where the VSSDK unit test library comes to the rescue! The library includes some helper classes to get you set up with mock objects which you can easily use for your package's unit tests.

For a great example of this, check out the C# Reference.Services sample in the latest release of the Visual Studio 2005 SDK. (You can find the unit tests stored in a TDD folder next to the .sln file.)

For those of you who are doing C++ development, you certainly haven't been left out. There is also a native unit testing harness and headers which allow you to mock up virtually any interface in Visual Studio. You can find this all in your VSSDK install under Common\Source\CPP\VSL\MockInterfaces and Common\Source\CPP\VSL\UnitTest.

Hopefully, you'll take advantage of the helps we've provided in the SDK to allow you to do more unit testing (and perhaps even test driven development) on your VSPackage.

For some more information on getting started with unit testing with mock objects, check out the following links and search around on Live.com: