C# – How should you look at unit testing protected members used by the abstract base class

cclass-designunit testing

I have the following class(es) that I want to write unit tests for:

public abstract class BaseClass
{
    public bool IsFooBar(Order order)
    {
        return order.IsNew && IsFooBarOverride(order);
    }

    protected abstract IsFooBarOverride(Order order);
}

public class SimpleDerivedClass : BaseClass
{
    protected override bool IsFooBarOverride(Order order)
    {
        // Return if the order is with a credit card.
    }
}

public class ComplexDerivedClass : BaseClass
{
    protected override bool IsFooBarOverride(Order order)
    {
        // Return a very complex statement
        // If the order is for a new customer
        // in New York, with an order amount of $500 or more
        // and has at opted for email subscriptions.
    }
}

The problem I am running into is that my derived classes contain the majority of my logic for determining the return value of IsFooBar(Order order). I want to test this logic to ensure it is proper. I was under the impression that you should only test the public API of a class, which is IsFooBar(Order order), which belongs to the base class.

  • Should I redesign my class structure by marking IsFooBar virtual and hope that other developers on the team use base.IsFooBar(order) as part of their return statement?

  • Should I leave my class structure in tact and test variations of the IsFooBar(Order order) method per derived class as a way to test the logic in the protected class?

Best Answer

Considering your doubts, I would argue that the choice of solving this with inheritance might be the wrong approach.

Perhaps composition would be more appropriate in this case? It is hard to tell without knowing the requirements.

To answer the question, as long as the template method is the way to go, test per derived class.