gpt4 book ai didi

c# - MSTEST 委托(delegate)人许可

转载 作者:IT王子 更新时间:2023-10-29 04:39:02 26 4
gpt4 key购买 nike

如何对装饰有 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 委托(delegate)人许可,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1106163/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com