| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
| Name | Name | Last commit date | ||
|---|---|---|---|---|
parent directory.. | ||||
A header-only C++ library that makes singletons unit testable without breaking existing code or APIs.
Traditional singletons are notoriously difficult to unit test. Their global state and hardcoded instance access make it nearly impossible to:
This creates a fundamental conflict: singletons provide architectural benefits but become testing liabilities.
SingletonBase see SingletonBase class solves this problem by providing a CRTP-based singleton framework that makes any singleton instantly testable while preserving 100% API compatibility. The key innovation is ScopedSingletonState see ScopedSingletonState class - an RAII class that temporarily replaces singleton instances during testing, enabling:
Transform any existing singleton into a testable one:
// Before: Untestable singleton
class MySingleton {
public:
static MySingleton& instance() {
static MySingleton inst;
return inst;
}
// ... methods
private:
MySingleton() = default;
};// After: Fully testable with same API
#include <PM/SingletonBase.h>
class MySingleton : public PM::SingletonBase<MySingleton> {
PM_SINGLETON(MySingleton) // Add this line
public:
static MySingleton& instance() { // Remove custom implementation
// SingletonBase provides this automatically
}
// ... all existing methods unchanged
private:
MySingleton() = default;
};Build testable singletons from the start:
#include <PM/SingletonBase.h>
class ConfigManager : public PM::SingletonBase<ConfigManager> {
PM_SINGLETON(ConfigManager)
public:
void setConfig(const std::string& key, const std::string& value);
std::string getConfig(const std::string& key) const;
private:
ConfigManager() = default;
std::unordered_map<std::string, std::string> config_;
};#include <PM/ScopedSingletonState.h>
void testConfigManager() {
// Get fresh instance for this test
PM::ScopedSingletonState<ConfigManager> testState;
// Test with isolated state
ConfigManager::instance().setConfig("key", "value");
assert(ConfigManager::instance().getConfig("key") == "value");
// Automatic cleanup - no test interference
}See Advanced Topics for best practices and Build Integration for setup instructions.
| Back | FazBrowse Home | New Git URL |