Mid SOLID

How do you test classes that use Singleton or static instances?

Testing singletons/statics is tricky due to global state. Best practices include:

  • Refactor to use interfaces and DI instead of static/singletons.
  • Wrap static calls behind interfaces so you can mock them.
  • Use specialized mocking tools (e.g., Microsoft Fakes) if refactoring isn't possible.
  • Avoid static state to improve testability.

More from Design Patterns in C#

All questions for this course