gpt4 book ai didi

c++ - expect_call,如何使用参数右值引用调用回调函数?

转载 作者:行者123 更新时间:2023-12-01 14:29:04 56 4
gpt4 key购买 nike

A 类正在测试中,我希望 EXPECT_CALL 立即返回,并为模拟的 asyncfunc() 方法调用值为 200(右值引用)的 lamda 函数。请阅读符合代码的注释

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

#include<iostream>
using namespace std;

// Concrete class
class B
{
public:
// asyncfunc signature, p2 is function pointer with argument as rvalue referrence
bool asyncfunc(int p1, std::function<void(int &&v)> &&p2, float p3){
cout << "asyncfunc() \n" << "param1 : " << p1 << "\nparam 3 : " << p3 << endl;
p2(100);
}

};

class MockB
{
public:
// asyncfunc mocked
MOCK_METHOD3(asyncfunc, bool (int, std::function<void(int &&v)> &&, float));
};

// unit under test - A
template< typename T>
class A
{
T *bobj;
void sync(){}
public:
A(T *pbobj):bobj(pbobj){}
void test_function()
{
bool value = bobj->asyncfunc(10, [this](int &&a){
cout << "Lamba : " << a << endl;
if(a == 100)
{
sync();
}
},
20);
cout << "test_function : " << value << endl;
}
};

//我的测试如下所示,出现编译错误

TEST(A, test_function)  
{
MockB b;
A<MockB> obj(&b);
using namespace ::testing;

EXPECT_CALL(b, asyncfunc(_,_,_)).WillOnce(DoAll(InvokeArgument<1>(100),Return(true)));
obj.test_function();
}

最佳答案

我不是 100% 确定,因为您的代码片段没有指定 lambda 是否返回某些东西 - 请遵循 'minimal, reproducible example' principle ,但我认为问题可能是 lambda 不返回任何类型 (void) 而您的模拟函数 asyncfunc 返回非 void 类型(例如 bool ).在这种情况下,您需要使用 Return 操作指定调用 asyncfunc 时应返回的内容:

struct MockClass {
MOCK_METHOD3(asyncfunc, bool(bool, std::function<void(bool)>, int));
};

TEST(MockTest, CallLambda) {
MockClass m{};

auto param{false};

EXPECT_CALL(m, asyncfunc(_, _, _)).WillOnce(DoAll(InvokeArgument<1>(param), Return(false)));

ASSERT_FALSE(m.asyncfunc(
true, [](bool) {}, 42)); // ASSERT_FALSE because `Return` action specified `false`
}

没有 DoAllReturn 操作,gmock 尝试使用 InvokeArgument 的结果作为 asyncfunc 的返回值它不能,因为它不能将 void 用作 bool

关于c++ - expect_call,如何使用参数右值引用调用回调函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63586778/

56 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com