Search code examples
c#tdd

TDD - Extract interface or make methods virtual


Whenever I want to stub a method in an otherwise trivial class, I most often extract an interface. Now if the constructor of that class is public and isn't too complex or dependent on complex types, it would have the same effect to just make the method in question virtual and inherit. Is this preferable over extracting an interface? If so, why?

Edit:

class Parser
{
    public IDictionary<string, int> DoLengthyParseTask(Stream s)
    {
        // is slow even with using memory stream
    }
}

There are two ways: Either extract an interface or make the method virtual. I actually prefer interfaces, but that could lead to an explosion of IParser Parser tuples...


Solution

  • You need to consider what you are trying to accomplish outside of your unit testing. Do not let your tool dictate your design.

    Dealing in interfaces can help decouple your code, but these should be natural points of separation in your code (e.g. business logic or data access). Making methods virtual makes sense if you are going to inherit and overwrite those methods.

    In your case, I would attempt to test the behavior that uses DoLengthyParseTask and not the method directly. This will provide a more robust test suite as well. You need to carefully consider whether this method really needs to be public(meaning it can and should be referenced outside its own assembly).