MSTEST的PrincipalPermissionMSTEST、PrincipalPermission

2023-09-03 05:47:00 作者:吻妳是不想失去妳

你如何单元测试code饰有属性的PrincipalPermission?

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

例如,此作品:

class Program
{
    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
        var c = new MyClass();
    }
}

[PrincipalPermission(SecurityAction.Demand, Role = @"BUILTIN\Users")]
class MyClass
{
    public MyClass()
    {
        Console.WriteLine("This works.");
    }
}

这则抛出SecurityException:

This throws a SecurityException:

[TestClass]
public class UnitTest1
{
    [TestInitialize]
    public void TestInitialize()
    {
        AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
    }

    [TestMethod]
    public void TestMethod1() 
    { 
        var c = new MyClass();
    }
}

任何想法?

推荐答案

如何创建一个 GenericIdentity 以及安装到 Thread.CurrentPrincipal中在测试像这样:

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();
}