C++ 如何在不依赖注入的情况下模拟遗留函数?
给定以下假设的遗留生产代码:C++ 如何在不依赖注入的情况下模拟遗留函数?,c++,unit-testing,googletest,C++,Unit Testing,Googletest,给定以下假设的遗留生产代码: struct Foo { Bar bar; bool baz() { return !bar.qux(); } }; 如何模拟bar.qux(),使其在一个测试中返回true,在另一个测试中返回false,而无需求助于 我使用的是框架,但不想为依赖注入添加太多接口。出于可测试性的目的,过多的接口往往会使生产代码过于复杂。我们可能可以这样做: #include <iostream> #includ
struct Foo
{
Bar bar;
bool baz()
{
return !bar.qux();
}
};
如何模拟bar.qux()
,使其在一个测试中返回true
,在另一个测试中返回false
,而无需求助于
我使用的是框架,但不想为依赖注入添加太多接口。出于可测试性的目的,过多的接口往往会使生产代码过于复杂。我们可能可以这样做:
#include <iostream>
#include <vector>
#include <deque>
// test/MockBarMonitorsAndControls.hpp
namespace test
{
bool const Bar_qux_default_output = true;
std::deque<bool> Bar_qux_outputs;
std::vector<int> Bar_qux_arg0_inputs;
}
// production/Bar.hpp
struct Bar
{
bool qux(int x);
};
// production/Bar.cpp
// bool Bar::qux(int x)
// {
// return static_cast<bool>(x & 2);
// }
// test/Bar.cpp
bool Bar::qux(int x)
{
test::Bar_qux_arg0_inputs.push_back(x);
if (!test::Bar_qux_outputs.empty())
{
auto result = test::Bar_qux_outputs.front();
test::Bar_qux_outputs.pop_front();
return result;
}
else
{
return test::Bar_qux_default_output;
}
}
// production/Foo.hpp
struct Foo
{
Bar bar;
int x = 9;
bool baz()
{
return !bar.qux(x);
}
void henry();
};
// test/BarTest.cpp
void TestBar1()
{
test::Bar_qux_outputs.clear();
test::Bar_qux_arg0_inputs.clear();
test::Bar_qux_outputs.push_back(false);
Foo foo;
bool pass = true;
auto result = foo.baz();
if (!result)
{
std::cout << "TEST1_ERROR: expected true result" << std::endl;
pass = false;
}
auto input = test::Bar_qux_arg0_inputs.front();
if (input != 9)
{
std::cout << "TEST1_ERROR: expected arg0 to be 9 but got " << input << std::endl;
pass = false;
}
if (pass)
{
std::cout << "TEST1 PASS" << std::endl;
}
else
{
std::cout << "TEST1 FAIL" << std::endl;
}
}
// test/BarTest.cpp
void TestBar2()
{
test::Bar_qux_outputs.clear();
test::Bar_qux_arg0_inputs.clear();
test::Bar_qux_outputs.push_back(true);
Foo foo;
foo.x = 21;
bool pass = true;
auto result = foo.baz();
if (result)
{
std::cout << "TEST2_ERROR: expected false result" << std::endl;
pass = false;
}
auto input = test::Bar_qux_arg0_inputs.front();
if (input != 21)
{
std::cout << "TEST2_ERROR: expected arg0 to be 21 but got " << input << std::endl;
pass = false;
}
if (pass)
{
std::cout << "TEST2 PASS" << std::endl;
}
else
{
std::cout << "TEST2 FAIL" << std::endl;
}
}
int main()
{
TestBar1();
TestBar2();
return 0;
}
如果您不想通过依赖项注入在运行时执行此操作,那么您可以通过针对替代实现进行链接,在链接时执行此操作。
TEST1 PASS
TEST2 PASS