c++ - 如何模拟 boost 抛出异常?

标签 c++ unit-testing boost googletest googlemock

我有使用 boost 与文件系统交互的代码,如下所示:

FileMigrater::migrate() const {
    //stuff
    try {
        boost::filesystem::create_direcotry(some_path_);
    } catch(const std::exception& e) {
        LOG(ERROR) << "Bad stuff happened";
        return MigrationResult::Failed;
    }
    //more stuff
}

我正在使用 gmockgtestmigrate 方法编写单元测试,我想为boost 抛出异常的情况。理想情况下,我想编写一个看起来像这样的单元测试(它的语法是错误的,因为我通常是新的 c++):

TEST_F(MyTest, boost_exception_test) {
    ON_CALL(boost_mock, create_directory()).Throw(std::exception);

    EXPECT_EQ(Migration::Failed, migrater.migrate());
}

问题是我不知道如何创建 boost_mock,甚至不知道这是解决问题的正确方法。

最佳答案

您的测试方法非常好。重点是 不能模拟自由函数,boost::filesystem::create_directory() 就是一个。

然而,documentation提出了一种解决方法:

It's possible to use Google Mock to mock a free function (i.e. a C-style function or a static method). You just need to rewrite your code to use an interface (abstract class).

Instead of calling a free function (say, OpenFile) directly, introduce an interface for it and have a concrete subclass that calls the free function:

class FileInterface {
public:
 ...
 virtual bool Open(const char* path, const char* mode) = 0;
};
class File : public FileInterface {
public:
 ...
 virtual bool Open(const char* path, const char* mode) {
  return OpenFile(path, mode);
 }
};

Your code should talk to FileInterface to open a file. Now it's easy to mock out the function.

This may seem much hassle, but in practice you often have multiple related functions that you can put in the same interface, so the per-function syntactic overhead will be much lower.

If you are concerned about the performance overhead incurred by virtual functions, and profiling confirms your concern, you can combine this with the recipe for mocking non-virtual methods.

关于c++ - 如何模拟 boost 抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33353337/

相关文章:

unit-testing - 测试生成的 Go 代码而不使用同位测试

c++ - boost 构建 : Use a feature or a variable

c++ - 递归在指数平方中的工作?

c++ - 为什么 Valgrind 在未释放 malloc 内存后不报告任何问题?

c++ - 什么是三法则?

无返回类型函数的 Javascript 单元测试

java - 测试类中的模拟接口(interface)

c# - 快速图中的无向图表示

c++ - boost python 对象的生命周期

c++ - 如何在没有内存泄漏的情况下返回对新对象的引用? C++