【问题标题】:Why does the gtest death test loop indefinitely为什么gtest死亡测试会无限循环
【发布时间】:2022-07-12 05:38:04
【问题描述】:

在我的项目中,我们使用 gtest 来模拟 blockbox 测试。出于这个原因,我们实现了一个 mockMain() 函数,其中包含应该在黑盒内的所有相关代码。然后我们使用 gtest 的 TEST_F 函数来执行该 main 并验证它生成的输出。现在的问题是:我想编写死亡测试,因为对于某些输入,程序应该退出。不幸的是,当我执行死亡测试时,它会无限循环。 由于实际的程序非常庞大,我试图在下面的代码中捕捉到发生的事情的本质。和主程序有同样的问题。

我发现在 Windows 上,死亡测试是在“线程安全”模式下执行的,它会重新运行整个程序。有办法改变吗?

ma​​in.cpp

bool runBlackboxTest = true;

int main(int argc, char *argv[])
{   //Only execute tests if flag is enabled
    if(runBlackboxTest){
        RectangleBlackboxTest::runAllTests();
        exit(0);
    }
    Rectangle oneRect(12.1, 7.4);
    std::cout << "Area: " << oneRect.getArea() << std::endl;
    return 0;
}

矩形.cpp

Rectangle::Rectangle(double a, double b){
    this->side_a = a;
    this->side_b = b;

    this->area = a*b;
}

double Rectangle::getArea(){
    return this->area;
}

double Rectangle::rectExit(){
    std::cout << "Exiting program." << std::endl;
    exit(1); 
    return 0;
}

RectangleBlackboxTest.cpp

using RectangleBlackboxDeathTest = RectangleBlackboxTest;

int RectangleBlackboxTest::runAllTests(){
    testing::InitGoogleTest();
    return RUN_ALL_TESTS();
}

//Just some example functinoality
void RectangleBlackboxTest::mockMain(){
    double a, b;
    srand(time(NULL));
    a = double(rand() % 100 + 1) / 17;
    b = double(rand() % 100 + 1) / 11;
    this->testingRect = new Rectangle(a, b);
    std::cout << "a: " << a << " b: " << b << " Area: " << this->testingRect->getArea() << std::endl;
}

//Imitating an exit in the mockMain()
void RectangleBlackboxTest::mockMainWithExit(){
    this->mockMain();
    this->testingRect->rectExit();
}

void RectangleBlackboxTest::TearDown(){
    delete this->testingRect;
}

//This is the part that loops indefinitely
TEST_F(RectangleBlackboxDeathTest, firstDeathTest){
    EXPECT_EXIT(mockMainWithExit(), testing::ExitedWithCode(1), ".*");
}

【问题讨论】:

    标签: c++ googletest


    【解决方案1】:

    对于任何有同样问题的人:

    主要问题在于testing::InitGoogleTest()

    当gtest发现死亡测试时,它会在Windows下使用createProcessA(...)创建一个新进程并传递额外的参数,以确保子进程只执行当前的死亡测试。 当子进程中没有将这些参数提供给testing::InitGoogleTest() 时,这会导致问题。在这种情况下它没有收到信息只执行死亡测试并重新开始运行整个测试代码,导致递归。

    TLDR:

    将命令行参数从main(int argc, char *argv[]) 传递到testing::InitGoogleTest()

    testing::InitGoogleTest(argc, argv)

    【讨论】:

      猜你喜欢
      • 2010-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-21
      • 2011-04-19
      • 2011-08-18
      • 2011-11-21
      相关资源
      最近更新 更多