如何忽略测试 DoAll() 中的第一个操作

How to ignore the first action in the gtest DoAll()

本文关键字:第一个 操作 何忽略 测试 DoAll      更新时间:2023-10-16

>I 声明一个函数

void MyFunction(const std::wstring& inParameter, std::wstring& outParamater);

第一个参数是传入参数,第二个是值输出参数,我想通过函数获取的值将通过outParameter传递它。

现在我嘲笑它

MOCK_METHOD2(MyFunction, void(const std::wstring&, std::wstring&));

但是,当我使用此模拟函数时:

std::wstring firstStr = L"firstStr";
std::wstring test = L"test";
EXPECT_CALL(*myGmockInstance, MyFunction(firstStr, _)).Times(1).WillOnce(DoAll(firstStr, SetArgReferee<1>(test)));

它不起作用。

我也试过

EXPECT_CALL(*myGmockInstance, MyFunction(_, _)).Times(1).WillOnce(DoAll(_, SetArgReferee<1>(test)));

EXPECT_CALL(*myGmockInstance, MyFunction(_, _)).Times(1).WillOnce(DoAll(firstStr, SetArgReferee<1>(test)));

EXPECT_CALL(*myGmockInstance, MyFunction(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<0>(firstStr), SetArgReferee<1>(test)));

我知道inParameterconst,所以我不能使用它SetArgReferee。但是如何设置它的值,同时我可以为outParameter设置值?

我认为你问题的标题很有误导性。据我了解,您只想为函数的第二个参数(输出参数(分配一些任意值。这是您可以使用Invoke来做到这一点的方法:

using ::testing::_;
void assignStringToArg(const std::wstring&, std::wstring& outputStr,
const std::wstring expectedStr) {
outputStr = expectedStr;
}
class SomeMock {
public:
MOCK_METHOD2(MyFunction, void(const std::wstring&, std::wstring&));
};
TEST(xxx, yyy) {
SomeMock someMock;
std::wstring firstStr(L"aaabbbccc");
std::wstring secondStr(L"I should change upon MyFunction call ...");
std::wstring expectedSecondStr(L"xxxyyyzzz");
EXPECT_CALL(someMock, MyFunction(firstStr, _)).Times(1).WillOnce(Invoke(std::bind(
&assignStringToArg,
std::placeholders::_1,
std::placeholders::_2,
expectedSecondStr)));
someMock.MyFunction(firstStr, secondStr);
ASSERT_EQ(expectedSecondStr, secondStr);
}

请注意,提供给Invoke的函数必须与您期望调用的函数具有相同的签名(这就是我使用bind的原因(。您可以使用谷歌宏ACTION_P达到相同的结果。我更喜欢使用Invoke,只是因为它对我来说看起来更干净。

由于您的情况相当简单,您也可以像以前尝试的那样使用SetArgReferee来完成:

EXPECT_CALL(someMock, MyFunction(firstStr, _)).Times(1).WillOnce(
SetArgReferee<1>(L"something"));
someMock.MyFunction(firstStr, secondStr);
ASSERT_EQ(L"something", secondStr);

我只是认为如果您只想执行一个操作,则使用DoAll毫无意义。 但是...如果你真的坚持:

EXPECT_CALL(someMock, MyFunction(firstStr, _)).Times(1).WillOnce(
DoAll(SetArgReferee<1>(L"something1"), SetArgReferee<1>(L"something2")));
someMock.MyFunction(firstStr, secondStr);
ASSERT_EQ(L"something2", secondStr);

这是一个相当愚蠢的例子,因为它将输出变量设置为L"something1"然后立即设置为L"something2"

相关文章: