
Turning Singleton Usage into Testable Code
See how you can wrap any singleton behind a protocol to make it injectable and your code fully testable 💯 The blog post shows how to deal with URLSession.shared usage. The same strategy can be applied to all other singletons in your code! The problem Service uses URLSession.shared directly. Tight coupling makes unit testing impossible without real network calls. struct PostsAPISerivce { func fetchPosts() async throws -> [Post] { let url = URL(string: ".../posts")! let (data, _) = try await URLSession.shared.data(from: url) return try JSONDecoder().decode([Post].self, from: data) } } In the sections, you’ll get step-by-step guide of making this service testable. These same steps can be applied to all other singletons found in your code. ...