简体   繁体   中英

Unit testing WCF service class with authentication and authorization enabled

I have a WCF service which is having UserName authentication and PrincipalPermission Authorization enabled.

How how can i unit test the method.

Service:

    [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 method:

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

when i try to execute the unit test i am getting error as:

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

how to unit test on classes which have authentication and authorization enabled.?

I solved this issue by creating a "setup" method and setting principal to current thread as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM