Is it possible to unit test a class that makes P/Invoke calls?

Question :

Is it possible to unit test a class that makes P/Invoke calls?,

Answer :

I want to wrap a piece of code that uses the Windows Impersonation API into a neat little helper class, and as usual, I’m looking for a way to go test-first. However, while WindowsIdentity is a managed class, the LogonUser call that is required to actually perform the logging in as another user is an unmanaged function in advapi32.dll.

I think I can work around this by introducing an interface for my helper class to use and hiding the P/Invoke calls in an implementation, but testing that implementation will still be a problem. And you can imagine actually performing the impersonation in the test can be a bit problematic, given that the user would actually need to exist on the system.

Read More  How do you create a shortcut to a directory so that it opens in explorer

,

Guideline: Don’t test code that you haven’t written.
You shouldn’t be concerned with WinAPI implementation not working (most probably it works as expected).
Your concern should be testing the ‘Wiring’ i.e. if your code makes the right WinAPI call. In which case, all you need is to mock out the interface and let the mock framework tell if you the call was made with the right params. If yes, you’re done.

  • Create IWinAPIFacade (with relevant WinAPI methods) and implementation CWinAPIFacade.
  • Write a test which plugs in a mock of IWinAPIFacade and verify that the appropriate call is made
  • Write a test to ensure that CWinAPIFacade is created and plugged in as a default (in normal functioning)
  • Implement CWinAPIFacade which simply blind-delegates to Platform Invoke calls – no need to auto-test this layer. Just do a manual verification. Hopefully this won’t change that often and nothing breaks. If you find that it does in the future, barricade it with some tests.
Read More  Designing a threaded commenting system

That’s the answer Is it possible to unit test a class that makes P/Invoke calls?, Hope this helps those looking for an answer. Then we suggest to do a search for the next question and find the answer only on our site.

Disclaimer :

The answers provided above are only to be used to guide the learning process. The questions above are open-ended questions, meaning that many answers are not fixed as above. I hope this article can be useful, Thank you