views:

406

answers:

4

I've used function and class templates in implementation of my libraries. So far I've just instantiated a template in the library unit-tests (CppUnit), and then proceeded to test it almost like any other normal class or function.

Recently I've been planning to add some templates also to the library APIs. Good interface is of course the most important thing, template or not. With well designed and implemented templates you can, if not totally prevent, at least make it more difficult for the user to shoot himself in the foot. Any way I feel that unit-testing public templates need to be a bit more rigorous, compared to purely internal templates.

So, how have you unit-tested your C++ templates? Have you come up with any elegant solutions, especially for templates in public library APIs?

+3  A: 

For starters, unit test your template code with the parameter you think is most likely for a user to supply. I've often made things templates "just in case" and end up never using anything but the one type I had in mind when I wrote the original code. So in that case, testing the most likely case covers all cases!

If you feel like you need to test more, use another template argument as different as possible from the first argument. It may not be necessary to test all methods again. Some methods may not actually depend on the template parameter.

John D. Cook
A: 

Instanciating the template in the unit test is the to test a template class.

What are the risks ? They depend what your library is doing with the template parameter ; think about what problems could arise depending on the class used to instanciate your template class and write new tests.

At least you will have your unit testing environment ready to reproduce any problem that will be reported.

philippe
+1  A: 
que que
Constraining template type arguments is important, +1 for mentioning it. Not doing it is like having all functions parameters type void*
A: 

Boost.Test has a component facilitating testing of templates against set of template parameters.