Unit testing protected methods

Problem Statement

We have a class FooRequirementHandler which inherits from and implements AuthorizationHandler<FooRequirement> - For details on what these handlers actually do see Custom Authorization Policy in this filters post.

We now have a protected access modifier to contend with. If we create an instance of FooRequirementHandler and try call HandleRequirementAsync the pre-compiler will protest with it being inaccessible due to its protection level. This is to be expected.

1
2
3
4
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, FooRequirement requirement)
{
// Handler things
}

Work Around

In the test create a class that inherits from FooRequirementHandler to expose the behavior.

A protected member is accessible within its class and by derived class instances.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/// <summary>
/// Additional setup required to expose `protected` behaviour
/// </summary>
public class ExposedFooRequirementHandler : FooRequirementHandler
{
public ExposedFooRequirementHandler(ISomeInterface someInterface)
: base(someInterface)
{

}

public async Task ExposedHandleRequirementAsync(AuthorizationHandlerContext context, FooRequirement requirement)
{
await base.HandleRequirementAsync(context, requirement);
}
}

In the unit test you can then use ExposedFooRequirementHandler as the class under test.

1
var classUnderTest = new ExposedFooRequirementHandler(someInterfaceMock.Object);