I've never written a unit test or any test for my c++ Programs. I know just that they are meant to testing if the function/program/unit does exactly what you think it does, But I have no idea how to write one.
Can anybody help me with a test for my example function? And what is meant with a test framework? Do I write tests for every function of my code and all the branches, or just the ones I think can be tricky?
doMode(int i) {
int a = fromString<int>(Action[i][1]);
int b = fromString<int>(Action[i][2]);
std::cout << "Parameter:\t" << a << "\t" << b << "\t" << std::endl;
Sleep(200);
return;
}
Edit: I'm not asking for a framework. or better: probably that is connected with my question. I just don't know where and how to start. What is the syntax I have to use? is it different depending on which framework I use?
This is how you would write a unit test without a framework.
#include <iostream>
// Function to test
bool function1(int a) {
return a > 5;
}
// If parameter is not true, test fails
// This check function would be provided by the test framework
#define IS_TRUE(x) { if (!(x)) std::cout << __FUNCTION__ << " failed on line " << __LINE__ << std::endl; }
// Test for function1()
// You would need to write these even when using a framework
void test_function1()
{
IS_TRUE(!function1(0));
IS_TRUE(!function1(5));
IS_TRUE(function1(10));
}
int main(void) {
// Call all tests. Using a test framework would simplify this.
test_function1();
}
You could start with no other library at all, just write a program that calls your function with different values and check the result if it matches the expectation.
Which will lead you to the insight that this function (with this design) is not easy to test ...
A test framework usually
"What to test" is always a good start for lengthy discussions. I would say, in an ideal world, yes, you test everything. In existing projects, start by writing tests for things that you add/change. In new projects, test as much as you can, maybe use TDD, use code coverage tools to check what you missed.
You should really read some introduction to unit testing (e.g this. But to give you some hints and answer some of your questions.
Choosing a test framework:
You can take whatever you prefer, but if you don't know which one to choose I would suggest to try GoogleTest which is very popular and has a nice documention.
Do I write tests for every function of my code and all the branches, or just the ones I think can be tricky?
You should write tests for every function and every branch of your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With