gmock与struct数据

时间:2017-11-09 13:44:50

标签: c++ struct gmock

我想用gmock验证函数参数。函数参数采用struct格式,如下所示:

SomeClass.h:

class SomeClass {
public:
    SomeClass();
    virtual ~SomeClass();
    struct SomeData {
        int Value;
        int Serie;
    };
    virtual void getData(SomeData &data);
};

SomeClass.cpp:

#include "../include/SomeClass.h"

    SomeClass::SomeClass(){}
    SomeClass::~SomeClass(){}

    void SomeClass::getData(SomeData &data){
        data.Serie = 4;
        data.Value = 5;
    }

MockSomeClass.h

#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "../include/SomeClass.h"

class MockSomeClass: public SomeClass {
public:
    MockSomeClass(){};
    virtual ~MockSomeClass(){};
    SomeData data;
    MOCK_METHOD1(getData, void(SomeData &data));
};

testSomeClass:

#include <gtest/gtest.h>
#include <gmock/gmock.h>

#include "../include/SomeClass.h"
#include "MockSomeClass.h"

using ::testing::_;
using ::testing::AtLeast;

TEST(testSomeMethod, test1){
    MockSomeClass mock1;
    SomeClass::SomeData data;
    EXPECT_CALL(mock1, getData(_)).Times(AtLeast(2));
    mock1.getData(data);
    mock1.getData(data);
}

TEST(testSomeMethod, test2){
    MockSomeClass mock2;
    SomeClass::SomeData data;
    EXPECT_CALL(mock2, getData(SomeClass::SomeData &data));
    mock2.getData(data);
}

当我运行testSomeClass时,test1没有错误但是test2导致了麻烦。有关如何将结构格式的数据包含在gmock函数调用中的任何建议吗?

1 个答案:

答案 0 :(得分:0)

在编写googlemock期望时:


EXPECT_CALL(someMock, someMethod(arg1, arg2, arg3, ...))...;

仅允许使用的参数(arg1,arg2,arg3)是匹配器-::testing::Matcher<T1>-其中T1是someMethod参数类型。幸运的是,可以从Matcher<T1>值构造T1值。

所以-不能使用SomeClass::SomeData &data-因为这是一些参数声明-而不是匹配器值。

您可能想使用::testing::Ref匹配器-例如:

EXPECT_CALL(mock2, getData(Ref(data)));