I'm currently refactoring an existing design, which was created without TDD. There is a class hierarchy with one abstract base class and two subclasses. In the original design, these classes were mostly just data holders without much behavior. I have identified some functionality which should be implemented in the base class, and I'd like to write tests for this functionality now. But since the class is abstract, I cannot instantiate it (obviously).
Note: The functionality I'd like to test doesn't invoke any pure virtual
methods.
class Base {}; // Is abstract
TEST(BaseTest, doesSomethingAmazing) {
Base aBase; // <-------- Not possible!!!
ASSERT_THAT(aBase.amazeMe(), Eq(AMAZING_RESULT));
}
Edit: To clarify a few things:
- Inheritance does actually make sense in this situation - both subclasses map to specific domain concepts, and polymorphism helps keep the surrounding code clean
- There is behavior which will be used in both subclasses, and which needs data that is common to both classes. So I think it makes sense to put it in a common super class.
I can think of several possible solutions, but none of them seems optimal to me:
- Add a subclass to the test code, which implements all
pure virtual
functions. Downside: Hard to name that subclass in a concise way, understanding the tests becomes harder - Instantiate an object of the subclass instead. Downside: Makes the tests pretty confusing
- Add empty implementations to the base class. Downside: Class is not abstract anymore
I tend towards option 3, to make the tests as clear as possible, but I'm not really satisfied with that. Is there a better way I'm not aware of?
Base
and then call the appropriate method. Alternatively, maybe you could factor out the method and put it in a separate helper class so it's easier to test?