Home > OS >  Assertion testing a void function
Assertion testing a void function

Time:02-10

I am writing a code with multiple void methods within a class, I am tasked with testing all of my methods using the "assert" from the c class <cassert. Here is one of my methods, that goes through the array in the class and trims the leading and trailing blank spaces. How would I write a function to test this method using assert? I am confused because there is no return value.

void trim_all() {
    // Iterate through all strings
    for (int i = 0; i < strSize; i  ) {
        // Initialize variables
        int begin = 0;
        int end = arr[i].size() - 1;
        // While loops to check how many spaces in front and back
        while (begin < arr[i].size() && arr[i][begin] == ' ') {
            begin  ;
        }
        while (end >= 0 && arr[i][end] == ' ') {
            end--;
        }
        // Update string to trimmed version
        arr[i] = arr[i].substr(begin, end - begin   1);
    }
}

CodePudding user response:

based on the code's implementation, you can check a result to fit with what the trim_all function do in your case the function delete all space at begin and end or the arr var. ex: input :

arr = "   abc  d  "
trim_all();
assert(arr == "abc  d");

CodePudding user response:

The function has side-effects. You're supposed to test that the side-effects are what they are supposed to be. This applies to all functions that have side-effects; not only those that return void. The function modifies elements of arr.

CodePudding user response:

I agree with paddy, asssert is not a good fit here - it will terminate your program on the first failure.

However, all test frameworks have their version of assertion, that would report the failure (optionally with details) and keep going.

For that later case, the assertion is trivial: iterate through your arr and make sure that each string doesn't begin or end with a space.

See this: Using ASSERT and EXPECT in GoogleTest

  • Related