如何对以PrincipalPermission属性修饰的代码进行单元测试?

例如,这有效:

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:
[TestClass]
public class UnitTest1
{
    [TestInitialize]
    public void TestInitialize()
    {
        AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
    }

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

有任何想法吗?

最佳答案

如何创建GenericIdentity并将其附加到测试中的Thread.CurrentPrincipal上,如下所示:

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

对于失败测试,​​您可以:
[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();
}

关于c# - MSTEST PrincipalPermission,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1106163/

10-10 13:47