是否可以对进行 P/Invoke 调用的类进行单元测试?
我想将一段使用 Windows Impersonation API 的代码包装到一个简洁的小帮助程序类中,并且像往常一样,我正在寻找一种先测试的方法。 但是,虽然 WindowsIdentity 是托管类,但实际以其他用户身份执行登录所需的 LogonUser 调用是 advapi32.dll 中的非托管函数。
我认为我可以通过引入一个供我的帮助程序类使用的接口并隐藏实现中的 P/Invoke 调用来解决此问题,但测试该实现仍然是一个问题。 您可以想象在测试中实际执行模拟可能会有点问题,因为用户实际上需要存在于系统上。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定我是否明白您的意思。您不想自己测试 PInvoke(您没有编写它),所以您想测试包装类是否按预期执行,对吗?
那么,只需在包装类中创建接口并对其进行测试即可吗?
就需要设置用户等而言,我认为这将是您需要咬住的一颗子弹。 模拟包装器 PInvoke 调用似乎很奇怪,因为您只需确认接口是否存在:)
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 :)
指南:不要测试您尚未编写的代码。
您不应该担心 WinAPI 实现无法正常工作(很可能它按预期工作)。
您应该关心的是测试“接线”,即您的代码是否进行了正确的 WinAPI 调用。 在这种情况下,您所需要做的就是模拟接口,并让模拟框架告诉您是否使用正确的参数进行了调用。 如果是的话,你就完成了。
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.