簡體   English   中英

如何使用 google mock 對自定義結構的向量 object 的內容進行單元測試和檢查?

[英]How do I unit test and check the contents of a vector object of a custom struct using google mock?

如果結構是

struct Point{
double x;
double y;
};

和 function 的 output 是vector<Point>並且大小為 10,我如何編寫 Google Test 或 Google Mock(我認為這更適合)來驗證向量的內容? 我可以在原始字符串中寫入預期的 output。

首先:手動編寫斷言,逐個元素檢查大小和內容是很好的:

std::vector<Point> MethodReturningVector();

TEST(MethodReturningVectorTest, CheckSizeAndFirstElementTest) {
    const auto result = MethodReturningVector();

    ASSERT_EQ(10, result.size());
    ASSERT_NEAR(42.f, result[0].x, 0.001f);
    ASSERT_NEAR(3.141592.f, result[0].y, 0.001f);
}

一旦你寫了很多不同的測試,你就會看到一個共同的斷言模式,然后你可以重構你的測試,一切都會自然而然地就位。

但是正如您提到的 GMock,確實有一些 GMock 技術可以使用。 有內置的匹配器來匹配類 STL arrays(我說類 STL 是因為它只需要開始和結束),例如ElementsAreElementsAreArray也存在)。 但是,它們要求數組中的元素可以進行比較。 這反過來要求為您的類型定義operator== (很少),因為默認的Eq匹配器正在使用它。 您可以使用其他內置匹配器(如AllOf (匹配器的聚合器)和Field (匹配結構的給定字段))為自定義類型定義自己的匹配器。 匹配器可以合並。 有關完整圖片,請參見(工作示例):

struct Point{
double x;
double y;
};

std::vector<Point> MethodReturningVector() {
    std::vector<Point> result(3);
    result[0] = Point{42.f, 3.141592f};
    return result;
}

MATCHER_P(Near, expected, "...") {
    constexpr auto allowed_diff = 0.001f;  // allow small diference
    if (!(expected - arg <= allowed_diff && arg <= expected + allowed_diff)) {
        *result_listener << "expected: " << expected << ", actual: " << arg;
        return false;
    }
    return true;
}

auto MatchPoint(Point p) {
    return testing::AllOf(testing::Field(&Point::x, Near(p.x)), 
                          testing::Field(&Point::y, Near(p.y)));
}

TEST(MethodReturningVectorTest, TestOneElement)
{
    const auto result = MethodReturningVector();
    
    ASSERT_EQ(result.size(), 3);
    ASSERT_THAT(result[0], MatchPoint(Point{42.f, 3.1415}));
}

TEST(MethodReturningVectorTest, TestWholeArray)
{
    const auto result = MethodReturningVector();
    
    ASSERT_THAT(result, testing::ElementsAre(
        MatchPoint(Point{42.f, 3.1415f}), 
        MatchPoint(Point{0.f, 0.f}), 
        MatchPoint(Point{0.f, 0.f})));
}

我強烈建議你從 GTest/GMock cookbook 等開始。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM