Why would you specifically want singletons in unittests? Even if your project uses one, you want that class scoped in testing or parallel execution and different orders will mess up your tests or have you clean up for each one.
Yeah, you're right. You wouldn't! If you have a service (service A) which depends on a singleton (service B), then they'd both be their own interface for the purposes of dependency injection. You'd mock out service B when testing service A & service A wouldn't ever know if they're dealing with a singleton or not. If you had a global, then this would be much more difficult and if you ever decide that service B wasn't going to be a singleton (i.e. think of notepad using a global text, then deciding that it wants to go to tabbed documents) then you can easily swap out the Singleton implementation of Service B to make it context-specific (or you could have multiple layers of service providers, but then it wouldn't truly be a singleton in that case).
View all comments
Show parent comment
2
u/Sheenius_Ger Sep 26 '26
Why would you specifically want singletons in unittests? Even if your project uses one, you want that class scoped in testing or parallel execution and different orders will mess up your tests or have you clean up for each one.