I'm big on unit testing, I like to test everything and I feel uncomfortable when I'm unable to write tests for some of my code. So even though some parts of your application are hard to test I'm willing to take some extra time to make them testable. In this post I want to show you some tricks I use to unit-test code that uses platform invoked functions.
As an example I'll use one of the invokes from my previous post, SetupDiClassNameFromGuid from the setupapi.dll. If you want to know more about what this does can read that post. Now let's take a look at some code.
I can see two problems here, testability and reusability. Let's start with making this more reusable although this has nothing to do with unit testing yet.
If you read the previous post you'll know that this call needs some pre-, and post-processing to get something usefull out of it. These technical details are not something you want to bother the consuming function with. DoSomethingThatNeedsToBeTested() just wants to pass a Guid in and get a string back. And in the real world there are probably more consumers of this imported function so you'll want to get rid of this duplicated code and hide it somewhere you can reuse it with a single call.
You can split out the preprocessing and postprocessing into a separate function but it would be better to go a bit further and just put everything in a separate class. I even made the DllImport private so the consumers are forced to use the code with all the wrapping code. I used the wrapper code from my previous post here to show how fast things get complex. In real life you'll probably want to add some errorhandling too.
Things are a bit more reusable now. But they're still not testable. And we've created a second problem. We don't just want to test the consuming code but we want to test the wrapper around _SetupDiClassNameFromGuid too.
The first problem is easy to solve. Just remove the static keyword from line 7. Then you can use dependency injection to inject this class into the consuming classes or functions and you can mock up everything. I'll show an example in my next post.
The second problem is a bit harder. I have a couple of solutions for this too but the are not very straight-forward and involve some extra code. I'll explain these later too.