单元测试启用了身份验证和授权的WCF服务类

时间:2014-09-29 11:45:39

标签: c# wcf unit-testing nunit wcf-security

我有一个WCF服务,它启用了UserName身份验证和PrincipalPermission授权。

如何对该方法进行单元测试。

服务:

    [PrincipalPermission(SecurityAction.Demand, Role = "Admin")]
    public void UploadEmployees(CustomerRequest request)
    {
        try
        {
            ProcessEmployees(request.PacketId, request.Employees);
        }
        catch (Exception ex)
        {
            throw new FaultException<CustomerException>(new CustomerException { Status = -1, ErrorMessage = ex.Message });
        }
    }

My Nunit测试方法:

    [Test]
    public void CallProcessEmployee_Should_Work()
    {
        var service=new CustomerService();
        var request = new CustomerRequest();
        service.UploadEmployees(request);
    }

当我尝试执行单元测试时,我收到错误:

System.Security.SecurityException : Request for principal permission failed.

如何对已启用身份验证和授权的类进行单元测试。

1 个答案:

答案 0 :(得分:5)

我通过创建&#34;设置&#34;解决了这个问题。方法和设置主要到当前线程如下:

    [SetUp]
    public void SetupUnitTestPrinciple()
    {
       var identity = new GenericIdentity("Unitest");
       System.Threading.Thread.CurrentPrincipal = new CustomPrincipal(identity);
    }