As mentioned in my first post about testing with permissions, this will be a more practical and straight forward approach on automated testing with permissions, let’s jump straight in!
Most of your test functions will consist of the following three components:
- Initialize and set up data
- Invoke the business logic that you want to test
- Validate that the business logic performed as expected
So if you want to perform a test with a permission set, you most likely only want to perform the invocation of the business logic with that permission set, because setting up data and verifying the outcome might require different (and maybe even unneeded) permissions.
While I was playing around with the problem as described above in mind I found out that it is possible to use the PermissionTestHelper dll directly in your test function instead of using it in the test runner.
Now we can use the AddEffectivePermissionSet function just before we invoke the business logic we want to test:
This requires the permission set to exist in the database, keep in mind that no error will be thrown if the permission set doesn’t exist and that you can ‘stack’ permission sets by calling the AddEffectivePermissionSet function multiple times.
PermissionTestHelper.Clear will result in unrestricted permissions again.
If you have your permission sets stored in code you can invoke that code in the initialize so it’s only executed once!