Mdjon26
Mdjon26

Reputation: 2255

Writing simple C++ tests

I've been tasked to write tests for some C++ code. I made a very simple function that reverses a string. I've wrote tests in C#, but never C++. What do C++ tests look like?

Here's my code: main takes a command line argument, sends it to reverse to reverse the string and returns it.

include <iostream>
#include <cstring>
using namespace std;

char * reverse(char *s)
{
    int len = strlen(s);
    char *head = s;
    char *tail = &s[len-1];
    while (head < tail)
        swap(*head++, *tail--);
    //cout << s <<endl;
    return s;

}

int main(int argc, char *argv[])
{
    char *s;
    for (int i=1; i < argc; i++)
    {
        s = reverse(argv[i]);
        cout << s<<endl;
    }

}

So, would a test, look something like?:

bool test()
{
   char *s = "haha3";
   char *new_s = reverse(s);
   if (new_s == "3ahah")
       return true;
   return false;

}

Is there a better way to do this? Syntax wise? Better looking code for testing C++ functions?

Upvotes: 1

Views: 2369

Answers (3)

wizurd
wizurd

Reputation: 3739

The preferred method for c++ unit testing is to use a testing framework such as Google Test or the Boost Test Framework.

Using Google Test, your test can be as simple as:

ASSERT_STREQ("cba", reverse("abc"));

Upvotes: 4

o11c
o11c

Reputation: 16136

There is no single standard framework. I prefer externally-driven tests over internally-driven ones, to avoid duplication of compile-time and test-run-time if I only change some of the source files.

TAP, which originated from Perl, is one standard that you can use with a library to implement your own tests and then use the prove harness.

Upvotes: 1

user5106417
user5106417

Reputation:

Well since its c++ you can do it like this:

#include <iostream>
#include <string>

int main()
{
    std::string test = "abc";
    std::cout << std::string(test.rbegin(), test.rend()) << std::endl;

    std::cin.get();
    return 0;
}

On a serious note, take a look at: Comparison of c++ unit test frameworks

Upvotes: 0

Related Questions