GoogleTest - 停用測試



一個好的測試框架應該具備臨時停用測試的功能。假設有一個測試因缺陷而失敗並且會阻塞其他測試。在這種情況下,唯一的解決方案就是停用測試,以便其他測試能繼續執行。這在一個功能仍處於開發階段且尚未準備好接受測試時也有幫助。

在 GoogleTest 中,你可以透過使用 DISABLED_ 字首或使用 GTEST_SKIP() 宏來停用測試。GoogleTest 是一個用於測試 C++ 程式碼的測試框架。

使用 DISABLED_ 字首

可以透過將測試名稱更改為 DISABLED_*,其中“*”表示測試的名稱,來標記測試為停用。透過此方法,當執行測試二進位制檔案時,GoogleTest 將跳過指定的測試。但是,測試仍然會被編譯。

語法

DISABLED_ 字首的語法如下 −

DISABLED_TestName

範例

在這個程式碼中,我們使用 DISABLED_ 字首在 GoogleTest 中停用了測試。

#include <gtest/gtest.h>

// function to be tested 
int divideNum(int nums1, int nums2) {
    if (nums2 == 0) {
        throw std::invalid_argument("Denominator cannot be zero");
    }
    return nums1 / nums2;
}

// test 1 
TEST(CheckDivison, ForPositiveInput) {
    EXPECT_EQ(12, divideNum(24, 2));
}

// test 2
TEST(CheckDivison, ForNegativeInput) {
    EXPECT_EQ(-2, divideNum(4, -2));
    EXPECT_EQ(-2, divideNum(-4, 2));
    EXPECT_EQ(2, divideNum(-4, -2));
}

// test 3
TEST(DISABLED_CheckDivison, ForZeroDenominator) {
    EXPECT_THROW(divideNum(4, 0), std::invalid_argument);
}

// main() function to run the test
int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

執行後,輸出將顯示如下 −

Test project D:/gTest/test2/build
    Start 1: CheckDivison.ForPositiveInput
1/3 Test #1: CheckDivison.ForPositiveInput .....   Passed    0.02 sec
    Start 2: CheckDivison.ForNegativeInput
2/3 Test #2: CheckDivison.ForNegativeInput .....   Passed    0.02 sec
    Start 3: CheckDivison.ForZeroDenominator
3/3 Test #3: CheckDivison.ForZeroDenominator ...***Not Run (Disabled)   0.00 sec

100% tests passed, 0 tests failed out of 2

Total Test time (real) =   0.13 sec

The following tests did not run:
          3 - CheckDivison.ForZeroDenominator (Disabled)

使用 GTEST_SKIP() 宏

GTEST_SKIP() 宏是 GoogleTest 在 1.10.0 版本釋出中新增的一項功能。它用於根據給定條件在執行時跳過測試。

語法

GTEST_SKIP() 宏的語法如下 −

GTEST_SKIP() << "Text to display";

範例

下面的程式碼展示瞭如何在 GoogleTest 中使用 GTEST_SKIP() 停用測試 −

#include <gtest/gtest.h>

// function to be tested
int prod(int num1, int num2) {
    return num1 * num2;
}

// to disable test 
bool disableTest(int num1, int num2) {
    if(num1 == num2) {
        return true;
    } else {
        return false;
    }
}

// Test suite
TEST(ProductTest, ForEqualNumbers) {
    int num1 = 3;
    int num2 = 3;
    if (disableTest(num1, num2)) {
        GTEST_SKIP() << "Disabling test";
    }
    ASSERT_EQ(prod(num1, num2), 9); 
}

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

上述程式碼的輸出如下 −

Test project D:/gTest/test3/build
    Start 1: ProductTest.ForEqualNumbers
1/1 Test #1: ProductTest.ForEqualNumbers ......***Skipped   0.03 sec

100% tests passed, 0 tests failed out of 1

Total Test time (real) =   0.10 sec

The following tests did not run:
          1 - ProductTest.ForEqualNumbers (Skipped)
廣告
© . All rights reserved.