Daily iOS
Testing

Unit testing around a singleton

An app calls AuthManager.shared directly all over the code. How would you unit test the code that depends on this singleton?

final class AuthManager {
    static let shared = AuthManager()
    private(set) var token: String?
    func login(_ id: String) async throws { token = try await API.login(id) }
}
How would an interviewer hear this answer? You'll see whether they'd move on, dig in, or say no, and which sentences would trip you up. Your score doesn't change.
See the short answer

Change the call sites to take an AuthProviding protocol type instead of using the singleton directly, and pass .shared as a default argument so existing code keeps working. Only the tests put a FakeAuth in.

Share a question