在 QT Creator 中捕获单元测试 - main 的多个定义

标签 c unit-testing qt-creator catch-unit-test

我想使用 Catch 单元测试框架来测试我的项目。我阅读了如何编写测试的教程,它非常简单。我尝试在 QT Creator 中创建非常简单的项目,其中包含以下文件:

main.cpp
tests.cpp
factorial.cpp
factorial.h
catch.hpp

main.cpp :

#include <stdio.h>
#include "factorial.h"

int main(void)
{
    printf("%d", factorial(5));
    return 0;
}

测试.cpp :

#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "factorial.h"

TEST_CASE( "factorial on valid numbers", "[factorial]" ) {
    REQUIRE( factorial(1) == 1 );
    REQUIRE( factorial(5) == 120 );
    REQUIRE( factorial(10) == 3628800 );
}

阶乘.cpp:

#include "factorial.h"

int factorial(int number)
{
    if(number < 0)
        return -1;
    int result = 1;
    for(int i = number; i > 0; i--)
        result *= i;
    return result;
}

阶乘.h :

#ifndef FACTORIAL
#define FACTORIAL

int factorial(int number);

#endif // FACTORIAL

catch.hpp是单元测试的catch框架

我在用 C 编写代码,而不是 C++,扩展名“.cpp”只是因为 catch,它不适用于扩展名为“.c”的文件

还有一个文件:testing.pro,里面有

MAKE_CFLAGS += -std=c99 -pedantic -Wall -Wextra
TEMPLATE = app
CONFIG += console
CONFIG -= app_bundle
CONFIG -= qt

SOURCES += \
    main.cpp \
    factorial.cpp \
    tests.cpp

include(deployment.pri)
qtcAddDeployment()

HEADERS += \
    catch.hpp \
    factorial.h

此文件由 QT creator 生成。

好的,我的问题是,当我尝试构建这个项目时,出现错误:“main 的多个定义”。

我明白了。我在 main.cpp 文件和 tests.cpp 中都有 main。但我不知道,我应该怎么做才能让它发挥作用。我想要一个项目,具有完全工作的主要文件和带有测试的文件,我可以在其中测试我的功能。我几乎到处搜索。我想我必须以某种方式在 QT Creator 中组织我的项目,但我不知道如何。我不知道它应该如何工作。

多谢指教

最佳答案

您确实有两条主电源:

  1. main.cpp 中的一个
  2. 根据您的要求,Catch 通过 CATCH_CONFIG_MAIN 宏定义提供了一个。

解决方案是要么删除宏并使用您的 main,要么省略您的 main 以使用 Catch 生成的宏。

更多信息在这里:Catch: Supplying your own main()

关于在 QT Creator 中捕获单元测试 - main 的多个定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30421834/

相关文章:

c++ - QFileDialog 打开第二个(可能是父级)不需要的窗口

c - C语言中的限定符是什么?

c - 在 C 中获取一个文件并返回一个数组

c++ - 如何提高套接字上的安全连接

unit-testing - 测试 Controller 是否有意义

c++ - 在 Qt Creator 中调试断言

c - Valgrind 在给出分配数量时究竟考虑了什么?

python - 如何模拟对象方法返回值

vue.js - 在 vitest 中使用模拟模块

Qt Creator 远程调试器