我有使用 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
}
我正在使用 gmock
和 gtest
为 migrate
方法编写单元测试,我想为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
,甚至不知道这是解决问题的正确方法。
最佳答案
您的测试方法非常好。重点是 googlemock不能模拟自由函数,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/