Make your C++ singletons testable in 2 lines!
Header-only C++ library for testable singletons. Add one macro, get instant testability.
#include <PM/SingletonBase.h>
class MySingleton : public PM::SingletonBase<MySingleton> {
PM_SINGLETON(MySingleton) // That's it!
public:
void setValue(int v) { value_ = v; }
int getValue() const { return value_; }
private:
int value_ = 0;
};#include <PM/ScopedSingletonState.h>
void testMySingleton() {
PM::ScopedSingletonState<MySingleton> scoped; // Fresh instance
MySingleton::instance().setValue(42);
assert(MySingleton::instance().getValue() == 42);
}No mocking. No setup. Just test directly.
| Class | Description | Reference |
|---|---|---|
SingletonBase<T> |
Testable singleton base | API |
ScopedSingletonState<T> |
Test instance replacement | API |
Advanced topics: Performance, Thread Safety, etc.
- Copy the
include/folder to your project - Add
include/to your compiler's include paths - Include headers:
#include <PM/SingletonBase.h>
Add this to your CMakeLists.txt:
add_subdirectory(path/to/SingletonBase)
target_link_libraries(your_target PM::SingletonBase)This automatically adds the include directory and excludes tests from your build.
MIT License - Do whatever you want with it! No restrictions, no strings attached.