如何使用 gmock 或 gtest 在此处模拟 CustomStream 外部依赖项?
#include <mylib/common/CustomStream.h>
namespace sender {
void Send(int p1){
mylib::common::CustomStream stream;
stream << p1;
}
}
如何使用 gmock 或 gtest 在此处模拟 CustomStream 外部依赖项?
#include <mylib/common/CustomStream.h>
namespace sender {
void Send(int p1){
mylib::common::CustomStream stream;
stream << p1;
}
}
使 CustomStream 从纯虚拟接口继承。然后将测试替身作为依赖项注入到函数中。例如:
namespace mylib {
namespace common {
class OutputStream {
virtual void Output(int value) = 0;
OutputStream& operator<<(int value) { this->Output(value); return *this; }
};
class CustomStream : public OutputStream {
virtual void Output(int value) { /*...*/ };
};
}
}
namespace sender {
void Send(OutputStream& stream, int p1) {
stream << p1;
}
}
namespace tests {
class MockOutputStream : public mylib::common::OutputStream {
MOCK_METHOD1(Output, void (int value));
};
TEST(testcase) {
MockOutputStream stream;
EXPECT_CALL(stream, Output(2));
sender::Send(stream, 2);
}
}
但是,当然,将每个类放在一个单独的头文件中。并且拥有一个没有类的函数(“发送”)也不是一个好主意,但我猜这是一个遗产。(注意:我没有尝试编译它。它是 Google Mock+Test-ish 语法。)