Files
Library/include/Void/TestingMock/Mock.hpp
T
2026-05-03 18:09:46 +03:00

81 lines
2.1 KiB
C++

#pragma once
#include <vector>
namespace Void::TestingMock
{
namespace Detail
{
/// Type-erased base for MockFunction<Sig>. The aggregate
/// MockBase::verify_all() walks a vector of these and calls
/// verify() on each.
class MockFunctionBase
{
public:
virtual ~MockFunctionBase() = default;
/// Verify all expectations were satisfied. Implementations
/// should be idempotent — verify_all() may be called
/// before MockFunction's destructor runs the same logic.
virtual void verify() = 0;
};
} // namespace Detail
/// Non-template aggregate base for Mock<Derived>. Holds non-owning
/// pointers to every MockFunction registered against this mock so
/// `verify_all()` can drive them collectively.
class MockBase
{
public:
virtual ~MockBase() = default;
void register_function(Detail::MockFunctionBase* fn)
{
m_functions.push_back(fn);
}
/// Verify every registered MockFunction. Each MockFunction
/// also verifies in its own destructor; calling verify_all()
/// explicitly produces failures earlier (before stack unwind)
/// with the mock's full context still on hand.
void verify_all()
{
for (auto* fn : m_functions) {
fn->verify();
}
}
private:
std::vector<Detail::MockFunctionBase*> m_functions;
};
/// CRTP base for user-defined mocks. Inherit alongside the interface
/// being mocked; declare MockFunction members initialized with
/// `*this` so they auto-register for `verify_all()`.
///
/// @code
/// class MockDb : public Mock<MockDb>, public Database {
/// public:
/// MockFunction<int(std::string_view)> get_user_id{*this,
/// "get_user_id"}; int get_user_id(std::string_view n) override {
/// return get_user_id(n); }
/// };
/// @endcode
template <typename Derived> class Mock : public MockBase
{
public:
Mock() = default;
~Mock() override = default;
Mock(const Mock&) = delete;
Mock& operator=(const Mock&) = delete;
Mock(Mock&&) = delete;
Mock& operator=(Mock&&) = delete;
};
} // namespace Void::TestingMock