MSTEST的PrincipalPermission [英] MSTEST PrincipalPermission
本文介绍了MSTEST的PrincipalPermission的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你如何单元测试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();
}
这篇关于MSTEST的PrincipalPermission的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文