Alagesan Palani
Alagesan Palani

Reputation: 2014

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.?

Upvotes: 3

Views: 1125

Answers (1)

Alagesan Palani
Alagesan Palani

Reputation: 2014

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

Upvotes: 7

Related Questions