Просто ради интереса я пытаюсь создать класс, который обеспечивает «базовую функциональность насмешки».
Более конкретно, вы можете устанавливать возвращаемые значения для вызовов функций.
Вот и все ;D
У меня есть решение, но оно мне не очень нравится.
Я покажу код, дам пояснения и расскажу, что мне в нем не нравится.
Я использую C++20.
#include
#include
#include
#include
#include
using namespace std;
class MockHelper {
public:
virtual ~MockHelper() = default;
template
void
setFunctionReturnValue(const string_view &functionName, Ret(Class::*functionPtr)(Args...), const Ret &returnValue) {
functionsReturnValues[functionName][type_index(typeid(functionPtr))] = make_any(returnValue);
}
protected:
template
Ret handleCall(const string_view &functionName, Ret(Class::*functionPtr)(Args...)) {
const auto &returnValues = functionsReturnValues[functionName];
const auto typeIndex = type_index(typeid(functionPtr));
if (!returnValues.contains(typeIndex))
return {};
return any_cast(returnValues.at(typeIndex));
}
private:
unordered_map functionsReturnValues;
};
class SomethingToMock : public MockHelper {
public:
int f() {
return handleCall("f", &SomethingToMock::f);
}
int g() {
// g is overloaded, thus we need to provide the template arguments explicitly
return handleCall("g", &SomethingToMock::g);
}
int g(bool) {
return handleCall("g", &SomethingToMock::g);
}
};
int main() {
SomethingToMock beingMocked;
// Setup expected return values
beingMocked.setFunctionReturnValue("f", &SomethingToMock::f, 0);
// again, g is overloaded, thus we need to provide the template arguments explicitly
beingMocked.setFunctionReturnValue("g", &SomethingToMock::g, 1);
beingMocked.setFunctionReturnValue("g", &SomethingToMock::g, 2);
// Show that this is actually working
std::cout
Подробнее здесь: https://stackoverflow.com/questions/784 ... -functions