开发者

How to unit test administrator-only functionality?

开发者 https://www.devze.com 2023-04-07 04:54 出处:网络
The design of my application is that standard user operations run first (and produce interested information even if the user cannot proceed) and then optionally offers to make some system changes acco

The design of my application is that standard user operations run first (and produce interested information even if the user cannot proceed) and then optionally offers to make some system changes accordingly, which requires elevation. If the user chooses to proceed, the program reruns itself requiring elevation with a command line switch that tells it where in the workflow to resume. The new process then picks back up where the old one left off and makes the changes the user requested.

My problem is I don't know how to write unit tests against the library methods that necessarily make privileged calls without running all of Visual Studio as administrator. I'd really like to avoid doing that so I'm fine with the system prompting me for credentials to run some or all of my unit tests. But currently as a standard user, the calls simply fail with the "System.Management.ManagementException: Access denied" exception.

Any ideas or experiences with handling this beyond elevat开发者_JAVA百科ing the whole of Visual Studio for the session? Since I'm using the built-in unit tests, ideally the solution would still display per-test results in the test results window but that's not a requirement.


I'm not sure what you are doing that requires administrator privileges, but I would suggest that in a unit test you shouldn't actually be calling those methods, but mocking out the classes that those methods are called on.

In this way you can make sure that the right calls are being made with the right parameters, but you aren't changing the state of the system.


You could impersonate an Admin account using LogonUser().

Take a look at this blog that’s trying to solve your problem.

I liked this codeproject implementation for calling LogonUser better. There's actually many codeproject examples of LogonUser() if you search around a little.

0

精彩评论

暂无评论...
验证码 换一张
取 消