I like the things that templates methods can do for me, since they can be used to dramatically simplify some code I’d otherwise have to write over and over.
However, I have a very hard time testing any classes that depend on collaborators that have public template methods. The real problem is they can’t be virtual, so my usual method of subclassing dependencies and stubbing doesn’t work.
Presently, my solution is to create a non-templated interface that includes every type that’s supported, then use the templates as an implementation detail. This is testable, but is tedious to update for large numbers of types passing through many classes. I suppose I could also redesign to use inheritance-based polymorphism instead, but if my problems with testing could be solved without a system redesign I’d prefer that.
I thought there might be something I could do with using template specialization to change the behaviour in my test library vs. my production library, but I’m not sure if that’s effective… or even possible.
So, what’s the best way of testing classes that use templated methods in their dependencies?
Google mock framework provides a way to create a mock with template parameters. Then you have to add a templated base class and pass a mock object to the constructor of the class under test.