MSTEST PrincipalPermission

前端 未结 2 1312
被撕碎了的回忆
被撕碎了的回忆 2021-01-03 23:17

How do you unit test code decorated with the PrincipalPermission attribute?

For example, this works:

class Program
{
    static void Main(string[]          


        
2条回答
  •  攒了一身酷
    2021-01-03 23:47

    How about creating a GenericIdentity and attaching that to the Thread.CurrentPrincipal in your test like so:

    [TestMethod]
    public void TestMethod1() 
    { 
        var identity = new GenericIdentity("tester");
        var roles = new[] { @"BUILTIN\Users" };
        var principal = new GenericPrincipal(identity, roles);
        Thread.CurrentPrincipal = principal;
    
        var c = new MyClass();
    }
    

    For a fail test, you could:

    [TestMethod]
    [ExpectedException(typeof(SecurityException))] // Or whatever it's called in MsTest
    public void TestMethod1() 
    { 
        var identity = new GenericIdentity("tester");
        var roles = new[] { @"BUILTIN\NotUsers" };
        var principal = new GenericPrincipal(identity, roles);
        Thread.CurrentPrincipal = principal;
    
        var c = new MyClass();
    }
    

提交回复
热议问题