Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 383
Rytmis Avatar asked Sep 10 '08 04:09

Rytmis


1 Answers

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.
like image 101
Gishu Avatar answered Sep 30 '22 13:09

Gishu