- this is not a question on how to write unit tests
- this is not a question on what to test
- this is a question on reducing the typing needed overall for a personal testing framework
I know you can send function pointers as arguments to functions in C.
Is there a c++98 version? Or, since c++ can work backwards, should I just use the C function pointer method?
I am trying to write a function that tests functions for me. I don’t want to write a long list of:
try {
func1()
out << fail
} except e {
out << pass
}
if (func2(arg2) == expected_val) {
out << pass
else
out << fail
try/catch...
try/catch...
if/else...
try/catch...
...etc
but maybe instead:
test_this(func1, passes_on_exception)
test_this(func2, ! passes_on_exception, expected_val2, arg2)
test_this(func3, passes_on_exception)
test_this(func4...
test_this(func5...
...etc
void test_this(func_name, pass_on_exception, expected_value, arg1, ..., argn) {
if pass_on_exception {
try {
func_name(arg1)
out << fail
} catch e {
out << pass
}
} else {
if func_name == expected_value {
out << pass
} else {
out << fail
}
}
}
Virtual functions seems out of the question since, if I recall correctly, the function names have to be overridden/hardcoded; as in, I would need to create a new class to inherit and override the functions, in which case, I would redeclare the function, and also retype all of those try/catch… the chain of try/catch/if/else seems better.
If there was a way to pass function names to other functions, I think I can figure it out from there. Unless the above is actually impossible in C++, then please stop me before I start, and I’ll just bear with that long list of try/catch/if/else unit testing method. So, main question: is there a way to do the above? If not, alternatives?
Yes you can use function pointers in C++, more generally you can use std::tr1::function for any sort of callable thing (function, method or lambda)
e.g.
// Use <functional> for C++11
#include <tr1/functional>
#include <iostream>
using namespace std;
using namespace std::tr1;
void first(function<void()> f)
{
f();
}
void second()
{
cout << "secondn";
}
int main()
{
first(second);
}
4