Unfortunately, MSTest does not have a built-in mechanism for this, and changes to the CAS policy application in .NET 4.0 severely limited the supported approaches for this.
The simplest approach to this would be to restrict the permission of the CAS permission on the AppDomain created by MSTest to run tests in a specific test assembly. However, current versions of MSTest do not allow you to intercept and / or configure the creation of AppDomain. We cannot get around this by adding code to the AssemblyInitialize method, because changes to the AppDomain policy made after running the code in AppDomain have no effect.
This basically leaves us with one supported mechanism for applying CAS permission restrictions for testing: using PermissionSet.PermitOnly from the test method or code that calls the test method. eg:.
[TestMethod] public void SomeTest() { SomeStaticTestUtilityClass.TargetPermissionSet.PermitOnly();
This can be done using custom test attributes using the approach described at http://blogs.msdn.com/b/vstsqualitytools/archive/2009/09/04/extending-the-visual-studio-unit-test-type- part-1.aspx . However, I have not tested this, and I am not sure that the mechanism for invoking the testing method will allow PermitOnly to be applied in such a way that it is present in the call stack for the tested code.
If you have a lot of them, so that the author and use of custom ITestMethodInvoker either does not work or otherwise does not work, another option is to use a post compiler such as PostSharp to insert PermitOnly calls.
If this does not work and you are not married to MSTest, you may also need to change your test environment to a more flexible one.
source share