如何模拟提升抛出异常?

How to mock boost throwing an exception?

我有使用 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.