Skip to main content

Unit testing and PInvoking pt. 2

In part one of this series of posts I explained how I usually set up PInvoke calls. I showed how to hide the calls themselves from consuming code so they don't have to duplicate the pre and postprocessing that's often needed. And I briefly showed how you could make the wrapper-calls non-static so you can mock the class they're in and that way test the consuming code. In this post I'll show exactly how to do this using the new Rhino Mocks 3.5 AAA model.

First let's see where we were,

   1: public class SetupApi
   2: {
   3:     [DllImport( "setupapi.dll", 
   4:         EntryPoint = "SetupDiClassNameFromGuid", 
   5:         CharSet = CharSet.Auto, 
   6:         SetLastError = true)]
   7:     private static extern bool SetupDiClassNameFromGuidEP(
   8:         ref Guid classGuid, StringBuilder className, UInt32 classNameSize, out UInt32 requiredSize);
   9:  
  10:     public virtual bool SetupDiClassNameFromGuid(Guid classGuid, out string className)
  11:     {
  12:         // 50 is a Sensible default value, if we're lucky it's enough
  13:         uint reqSize = 50;
  14:         bool returnValue;
  15:         StringBuilder classNameBuilder = new StringBuilder((int)reqSize);
  16:  
  17:         // First try.
  18:         returnValue = SetupDiClassNameFromGuidEP(
  19:             ref classGuid, classNameBuilder, (uint)classNameBuilder.Capacity, out reqSize);
  20:  
  21:         if ((uint)classNameBuilder.Capacity != reqSize)
  22:         {
  23:             // call again with the right size stringbuilder
  24:             classNameBuilder.Capacity = (int)reqSize;
  25:             returnValue = SetupDiClassNameFromGuidEP(
  26:                 ref classGuid, classNameBuilder, reqSize, out reqSize);
  27:         }
  28:  
  29:         className = classNameBuilder.ToString();
  30:         return returnValue;
  31:     }
  32: }

We put the DllImport in a separate class, the import itself is made private and the wrapper is public. I fixed some errors in this code. We have a different name for the DllImport so we need to specify an entrypoint. And I made the wrapper function virtual to be able to mock it.


The consuming code now looks something like this:



   1: public class Consumer
   2: {
   3:     public SetupApi SetupApi { get; protected set; }
   4:  
   5:     public Consumer(SetupApi setupApi)
   6:     {
   7:         SetupApi = setupApi;
   8:     }
   9:  
  10:     public void DoSomethingThatNeedsToBeTested()
  11:     {
  12:         Guid classGuid = Guid.Empty;
  13:         string className = string.Empty;
  14:         //..
  15:  
  16:         SetupApi.SetupDiClassNameFromGuid(classGuid, out className);
  17:  
  18:         //..
  19:     }
  20: }

I used constructor dependency injection to inject the SetupApi. The DoSomethingThatNeedsToBeTested method does stuff, calls SetupApi.dll and does some more stuff. Now let's take a look at how we can test this.


I'll use RhinoMocks with the new AAA model to mock and test the calls to the SetupApi. I can explain how I do this but I think the code speaks for itself. If I want to test if the right call is made for example I can use the following test:



   1: [Test]
   2: public void ConsumerCallsApi()
   3: {
   4:     SetupApi api = MockRepository.GenerateMock<SetupApi>();
   5:     Consumer sut = new Consumer(api);
   6:     string test;
   7:  
   8:     api.Expect(x => x.SetupDiClassNameFromGuid(Guid.Empty, out test))
   9:         .IgnoreArguments()
  10:         .Return(true);
  11:  
  12:     sut.DoSomethingThatNeedsToBeTested();
  13:  
  14:     api.VerifyAllExpectations();
  15: }

You could hide SetupApi behind an interface if you want to create your own mock implementations instead of relying on a mocking framework. I like to use rhino mocks for most of my mocking.


In the next post in this series I'm going to look at a couple of ways to test the implementation of the wrapper function around the call. This is a bit harder and for simple wrapper functions the workarounds I show might be a bit too much trouble.


kick it on DotNetKicks.com

Comments

Popular posts from this blog

Using xUnit.Net with .Net 4.0

I’ve been using xUnit.Net for a while now. It’s just a tiny bit cleaner and slightly less abrasive than other .Net unit testing frameworks. Leaving out unnecessary stuff like [TestFixture] and shortening Assert.AreEqual to the equally clear but shorter Assert.Equal don’t seem like big improvements but when you type them several times a day tiny improvements start to add up. I also like the use of the [Fact] attribute instead of [Test]. It shifts the focus from testing to defining behavior. So how do we get all this goodness working with the Visual Studio 2010 beta?

Square One available on the Android market

This is just a short post to let you know that a first version of the Android app I’ve been working on for the last couple of weeks is available on the Android market. The app is called Square One and it’s a simple bassline synthesizer. It’s free so try it out and let me know what you think of it, but be prepared it’s still an early version. I hope to add more features in the next few months and maybe build something that can be used to create real music.The lower part of the screen contains the sequencer controls that can be used to program your own bass lines. On the left is a four by four grid of buttons where you can select a step in the sequence. On the right you can select the note to be played on that step. When you’re done you can press Start and the sequence starts playing. The knobs on the top can be used to control a couple of parameters from the synthesizer engine that creates the sound. You can control the cutoff frequency and resonance of the low-pass filter, attack and …

Building Android projects with Jenkins, Ant and Mercurial

I have recently set up a Jenkins build server for my Android projects hosted on Bitbucket. It’s not difficult but there are a couple pitfalls and the information on how to do this isn’t available from one single place so I decided to document the process and put up the information over here. Maybe other people will benefit from having a step-by-step guide too.