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,
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:
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:
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.