Unit Test and Impersonation
Usually as a developer I am logged with a user with more rights than a usual user. Even if I am not using the Admin account often I have to create one or more user with associated groups to simulate my target environment and log with those user and test my application. This is time consuming for me and i want to be sure I can retest those cases as often and as fast as I want. The idea may seem strange as those tests looks more like integration tests, but i don’t want to deploy my application, test manually with different accounts the expected behavior and play ping pong between integration and dev environment to correct the issues.
So I need to test the behavior of my code according to the rights of the user running it (this is all about Authorization). This can occur when access to classes or methods are limited to some users, when external resources (DB, Files…) with specific rights are involved.
To industrialize this in Unit Tests I am using an Helper class with Unmanaged code.
Create an Unmanaged project with the following code :
|
|
This helper class will manage the impersonation.
In my Test Classes, I create a new test project referencing the helper class we created above and I am writing my tests as follow:
Negative Test : Trying to log with an inexistent user.
|
|
Positive and Negative Test. According to how the code is implemented the content of the test will change. The aim is to use the different user privileges on all the securable. The content of the Assert statements will vary and or the [ExpectedException(typeof(namespace.NamedException))] attribute can also be used.
|
|
Possible Optimizations As I used those tests, I realized a way to implement tests more easily is to create one Test Class per user and create the impersonation context in the ClassInitialize() methods. It makes the code much more readable.
Before using this solution I have been looking for an Attribute to give the credentials i wanted to use for the test.
I was thinking it would be nice to add that feature, but at the moment I m mitigated. I don’t think Unit Test are a
good place to test security yet in my case this was the best place to do it.
Sources: [MSDN : System.Security.SecurityContext] ( http://msdn.microsoft.com/en-us/library/system.security.securitycontext.aspx )