我的模拟定义如下:
template<typename T>
class ParseTreeMock : public ParseTreeInterface<T> {
public:
MOCK_METHOD1(fillConfigTree, void(std::string const&));
MOCK_METHOD1_T(getProperty, T(std::string const&));
ParseTreeMock(): parseTree(std::make_unique<pt::ptree>()) {
}
static std::unique_ptr<ParseTreeInterface<T>> getDefaultTree() {
return std::make_unique<ParseTreeMock<T>>();
}
private:
std::unique_ptr<pt::ptree> parseTree;
};
稍后在测试用例中创建:
class ConfigTest : public ::testing::Test {
protected:
std::unique_ptr<ParseTreeInterface<std::string>> treeMock;
virtual void SetUp() {
treeMock = ParseTreeMock<std::string>::getDefaultTree();
}
};
我想在getProperty方法上设置返回特定值:
EXPECT_CALL(*treeMock, getProperty("miniReaderConfig.cacheConfig.cacheOnOff")).willOnce(Return(false));
我收到错误:
In file included from ./lib/googletest/googlemock/include/gmock/gmock-generated-function-mockers.h:43:0,
from ./lib/googletest/googlemock/include/gmock/gmock.h:61,
from ./test/UT/Mocks/ParseTreeMock.hpp:2,
from test/UT/Configuration/ConfigTest.cpp:1:
test/UT/Configuration/ConfigTest.cpp: In member function ‘virtual void ConfigTest_CreateConfigurationWithoutErrors_Test::TestBody()’:
./lib/googletest/googlemock/include/gmock/gmock-spec-builders.h:1844:12: error: ‘class miniReader::Configuration::ParseTreeInterface<std::__cxx11::basic_string<char> >’ has no member named ‘gmock_getProperty’; did you mean ‘getProperty’?
((obj).gmock_##call).InternalExpectedAt(__FILE__, __LINE__, #obj, #call)
任何解释错误的解决方案都会受到赞赏。
答案 0 :(得分:1)
treeMock
变量必须是std::unique_ptr<ParseTreeMock<std::string>>
类型,然后静态方法需要看起来像这样
static std::unique_ptr<ParseTreeMock<T>> getDefaultTree()
{
return std::make_unique<ParseTreeMock<T>>();
}
通常,您实例化一个在测试中实现接口的类,然后将该实例传递给您正在测试的类,并使用EXPECT_CALL
确保您正在测试的类调用您的回调。模拟对象。
与您获得的错误无关,但WillOnce
需要拼写首字母大写。此外,由于您将模板变量设置为std::string
,因此EXPECT_CALL
无法期望返回布尔值。
这为我编译:
namespace pt { struct ptree {};}
template<typename T>
class ParseTreeInterface
{
public:
virtual void fillConfigTree(std::string const&) = 0;
virtual T getProperty(std::string const&) = 0;
};
template<typename T>
class ParseTreeMock : public ParseTreeInterface<T> {
public:
MOCK_METHOD1(fillConfigTree, void(std::string const&));
MOCK_METHOD1_T(getProperty, T(std::string const&));
ParseTreeMock(): parseTree(std::make_unique<pt::ptree>()) {
}
static std::unique_ptr<ParseTreeMock<T>> getDefaultTree()
{
return std::make_unique<ParseTreeMock<T>>();
}
private:
std::unique_ptr<pt::ptree> parseTree;
};
class ConfigTest : public ::testing::Test {
protected:
std::unique_ptr<ParseTreeMock<std::string>> treeMock;
virtual void SetUp() {
treeMock = ParseTreeMock<std::string>::getDefaultTree();
}
};
TEST_F(ConfigTest, test)
{
EXPECT_CALL(*treeMock, getProperty("miniReaderConfig.cacheConfig.cacheOnOff")).WillOnce(::testing::Return(""));
}