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

Running a Git repository on Ubuntu using Gitosis

20I’ve been using Git for a couple of small projects that I’ve been hosting on github.com but version control for my bigger ‘secret’ projects still runs on a windows machine with visual svn server.Now that I’m starting to use Mono for a couple of projects so I’m playing with linux more. Last week I decided to try to try out gitosis on an ubuntu server. I found out it’s pretty easy to use when you know your way around git but for a noob like me some things weren’t immediately clear. Eventually I solved most problems I ran into, so I decided to write up the steps I took to install gitosis on ubuntu 10.04

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 …

Android development resource links

I've been playing with the Android SDK and I have a growing list of bookmarks to Android dev resources for my own use. I thought the best place to keep them would be here on my blog. That way other people can benefit too. I'll keep updating this list so feel free to add suggestions in the comments.