Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

I am not sure if I follow you.. You don't want to test the PInvoke yourself (you didn't write it) so you want to test that the wrapper class is performing as expected right?

So, just create your interface in the wrapper class and test against that?

In terms of needing to set up users etc, I think that would be a bullet you need to bite. It would seem odd to mock a wrapper PInvoke call, since you would simply just confirm and interface exists :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top