#pragma once #include #include #include #include #include #include #include #include #include namespace Void::TestingMock { template class MockFunction; template class MockFunction : public Detail::MockFunctionBase { using Expectation = Detail::Expectation; public: /// Standalone constructor — no auto-registration. The /// destructor will still call verify() so isolated tests work /// without a Mock wrapper. explicit MockFunction(std::string name = "unnamed_mock") : m_name(std::move(name)) { } /// Owner-aware constructor — registers with `owner` so /// `owner.verify_all()` drives this mock's verify(). MockFunction(MockBase& owner, std::string name = "unnamed_mock") : m_name(std::move(name)) { owner.register_function(this); } ~MockFunction() override { verify(); } MockFunction(const MockFunction&) = delete; MockFunction& operator=(const MockFunction&) = delete; MockFunction(MockFunction&&) = delete; MockFunction& operator=(MockFunction&&) = delete; template Expectation& expect(std::source_location loc, MArgs&&... matchers) { auto exp = std::make_shared( typename Expectation::MatcherTuple{ MatcherHolder>( std::forward(matchers))...}, loc); m_expectations.push_back(exp); return *exp; } template Expectation& expect(MArgs&&... matchers) { return expect(std::source_location::current(), std::forward(matchers)...); } R operator()(Args... args) { std::lock_guard lock{m_mutex}; for (auto& exp : m_expectations) { if (!exp->is_saturated() && exp->matches(args...)) { exp->record_call(); return exp->execute(args...); } } Void::Testing::fail(build_unmatched_message(args...)); if constexpr (!std::is_same_v) { return R{}; } } void verify() override { for (auto& exp : m_expectations) { exp->verify(m_name); } m_expectations.clear(); } private: std::string m_name; std::vector> m_expectations; std::mutex m_mutex; /// Build a multi-line error message that names the actual /// arguments and lists every registered expectation with its /// matcher tuple and call counts. std::string build_unmatched_message(const Args&... args) const { std::string msg = std::format("no expectation matched call to {}({})", m_name, render_args(args...)); if (m_expectations.empty()) { msg += "\n (no expectations registered)"; return msg; } for (std::size_t i = 0; i < m_expectations.size(); ++i) { const auto& exp = *m_expectations[i]; msg += std::format("\n expectation {}: {} — {}/{} calls", i + 1, exp.describe_matchers(), exp.call_count(), exp.max_calls()); } return msg; } static std::string render_args(const Args&... args) { std::string out; bool first = true; auto append = [&](const auto& a) { if (!first) { out += ", "; } out += Void::Testing::Detail::repr(a); first = false; }; (append(args), ...); return out; } }; } // namespace Void::TestingMock