【问题标题】:Writing simple C++ tests编写简单的 C++ 测试
【发布时间】:2015-10-03 21:45:39
【问题描述】:

我的任务是为一些 C++ 代码编写测试。我做了一个非常简单的函数来反转一个字符串。我用 C# 写过测试,但从来没有用 C++ 写过。 C++ 测试是什么样的?

这是我的代码:main 接受一个命令行参数,将其发送到 reverse 以反转字符串并返回它。

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

}

那么,测试会看起来像吗?:

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

}

有没有更好的方法来做到这一点?语法明智?用于测试 C++ 函数的代码更好看?

【问题讨论】:

  • 我会从不尝试反转只读文字开始。
  • C++ 语言没有“测试”的概念,C# 也没有。您正在使用一些添加它们的库。

标签: c++ testing


【解决方案1】:

好吧,因为它是 c++,你可以这样做:

#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;
}

认真的看一下:Comparison of c++ unit test frameworks

【讨论】:

    【解决方案2】:

    c++ 单元测试的首选方法是使用测试框架,例如Google TestBoost Test Framework.

    使用 Google Test,您的测试可以很简单:

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

    【讨论】:

      【解决方案3】:

      没有单一的标准框架。我更喜欢外部驱动的测试而不是内部驱动的测试,如果我只更改一些源文件,以避免编译时和测试运行时的重复。

      源自 Perl 的 TAP 是一种标准,您可以将其与库一起使用来实现您自己的测试,然后使用 prove 工具。

      【讨论】: