How do I write a unit test in c++?

12,010

Solution 1

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();
}

Solution 2

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

  • takes away the burden of writing a main() function that calls all the tests
  • allows to write multiple test functions
  • provide features like test-setup per test program/per test function
  • and much more

"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.

Share:
12,010
tinkerbell
Author by

tinkerbell

Updated on July 30, 2022

Comments

  • tinkerbell
    tinkerbell almost 2 years

    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?