gpt4 book ai didi

c++ - 如何实例化 std::exception_ptr 以进行单元测试

转载 作者:行者123 更新时间:2023-12-03 07:49:51 26 4
gpt4 key购买 nike

我有一个运行异步网络工作线程的系统,并定期检查该工作线程是否存储了一些std::exception_ptr。在这种情况下,它可能会抛出错误,或以其他方式报告错误。简单的例子:

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

// simplified Network interface and the mock
struct INetwork {
virtual std::exception_ptr getExceptionPtr() const = 0;
};
struct MockedNetwork: public INetwork {
public:
MOCK_METHOD(std::exception_ptr, getExceptionPtr, (), (const override));
};
// simplified system
class System {
public:
System(INetwork& network): _network{network} {}
void run() {
// some complex logic
std::exception_ptr exPtr = _network.getExceptionPtr();
if (exPtr) {
// error handling, or just rethrow
std::rethrow_exception(exPtr);
}
}
private:
INetwork& _network;
};

然后我想针对以下场景测试我的代码

Whenever Network reports an error through exception_ptr, System shall rethrow this exception

所以我有这个小的 gtest 测试用例:

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

struct MyException: public std::runtime_error {
MyException(): std::runtime_error("MyException") {}
};

TEST(Demo, demo) {
MockedNetwork mockedNet;
EXPECT_CALL(mockedNet, getExceptionPtr()).WillRepeatedly([]() -> std::exception_ptr{
return nullptr; // this is OK, but I want to simulate an error, not error-free run
// return new MyException; // this doesn't compile, and anyway seems like a bad idea
});
System sut(mockedNet);
ASSERT_THROW(sut.run(), MyException);
}

如何模拟我的模拟网络返回 std::exception_ptr 的情况,其中包含指向可以重新抛出的自定义异常的指针?

最佳答案

std::make_exception_ptr :

std::exception_ptr e = std::make_exception_ptr(MyException{});

关于c++ - 如何实例化 std::exception_ptr 以进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77496281/

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