Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a good way to unit test templated c++ methods/classes/functions?

I'm looking for a good way to unit test my templated methods, classes, and functions in c++. I have a feeling that it is not enough to just test using with a single type, and it doesn't feel right to just duplicate the unit tests and replace the types.

To be more specific, I'm working on a Matrix class and using Boost's unit testing framework. The Matrix is to work with different types. It will mainly be used for basic types, but I would like it to support concrete types too.

Note, I doing this for learning purposes, which is why I'm not using a existing matrix implementation.

like image 881
jpihl Avatar asked Apr 20 '12 13:04

jpihl


People also ask

What can be used for unit testing in C?

The most scalable way to write unit tests in C is using a unit testing framework, such as: CppUTest. Unity. Google Test.

What makes a good unit test?

Good unit tests should be reproducible and independent from external factors such as the environment or running order. Fast. Developers write unit tests so they can repeatedly run them and check that no bugs have been introduced.


2 Answers

Boost test has a macro BOOST_AUTO_TEST_CASE_TEMPLATE that runs a test on a template for each type in a boost::mpl::list.

template<typename T>
T Add(T lh, T rh)
{
   return lh + rh;
}

typedef boost::mpl::list<int, float> test_types;

BOOST_AUTO_TEST_CASE_TEMPLATE(Add_1Plus2_Is3, T, test_types)
{
    T result = Add(T(1), T(2));
    BOOST_CHECK_EQUAL(T(3), result);
}

http://www.boost.org/doc/libs/1_48_0/libs/test/doc/html/utf/user-guide/test-organization/auto-test-case-template.html

like image 184
hansmaad Avatar answered Oct 21 '22 08:10

hansmaad


I agree with josuegomes and VJovic. I think, one way to minimize duplication of code is to make a templated function with your unit test logic and then call this with the different type arguments. This way, you are able to place all of your Matrix unit testing logic one place, while calling the templated unit test function once per each desired type.

However, it might be overkill to do so. I think it depends on the amount of logic in your tests.

like image 44
Lasse Christiansen Avatar answered Oct 21 '22 09:10

Lasse Christiansen