What is a correct way to use one implementation of unit test to test two completely different functionalities. In other words, I would like to have two (or more) tests that execute identical code for testing, but differ only in one place - just like in the code below:
TEST(SomeClass, someFunctionality)
{
// Initialize test (identical)
// ...
for (unsigned i = 0; i < 128; i++) {
// Prepare iteration (identical)
// ...
// One test calls here function A() and second test calls function B()
// and here is the only difference - multiple lines computing arguments
// for each function call
// ...
// Finalize iteration (identical)
// ...
}
// Finalize test (identical)
// ...
}
You could make a function that both tests share, and pass it a lambda containing the code unique to each test:
template<typename Func>
void testFunctionality(Func func)
{
// Initialize test
// ...
for (unsigned i = 0; i < 128; i++) {
// Prepare iteration
// ...
func();
// Finalize iteration
// ...
}
// Finalize test
// ...
}
TEST(SomeClass, someFunctionality)
{
testFunctionality([]() { A(); });
}
TEST(SomeClass, someOtherFunctionality)
{
testFunctionality([]() { B(); });
}
You can pass the lambda function whatever arguments you need, e.g. the current iteration i
or other local parameters.