Singleton with Swift 3.0

前端 未结 6 1666
灰色年华
灰色年华 2021-01-15 04:33

I had this implementation with Swift 2.0 and the Xcode suggestion is not only baffling but causes compilation error as well. it\'s a library where users are passing callfunc

6条回答
  •  北恋
    北恋 (楼主)
    2021-01-15 05:01

    The answers to date are great, but I like to be able to test my classes that use singleton with unit tests. The existing solutions require that you get a real singleton, not one that you can Fake, Mock, and Stub. In order to make testing easier, I use something like this:

    protocol ScheduleManaging {
        func add(_ schedule: TimerSchedule)
    }
    
    class ScheduleManager: ScheduleManaging {
        var schedule: TimerSchedule?
    
        static var sharedInstance: ScheduleManaging = {
            return ScheduleManager()
        }()
    
        private init() {
        }
    }
    
    typealias ScheduleManagingMethods = ScheduleManager
    extension ScheduleManagingMethods {
        func add(_ schedule: TimerSchedule) {
            self.schedule = schedule
        }
    }
    

    In classes under test that use the singleton, I can do something like this:

    class OtherTests: XCTestCase {
    
        class FakeSharedManager: ScheduleManaging {
            var addMethodCalled = false
            func add(_ schedule: TimerSchedule) {
                addMethodCalled = true
            }
        }
    
        func test_SomeMethodThatShouldCallAdd_CallsAdd() {
            ScheduleManager.sharedInstance = FakeSharedManager()
            // Test that some class that uses the ScheduleManager
            // calls the "add" method of the ScheduleManager
            let someClass = ManagerUsingClass()
            someClass.someMethodThatShouldCallAdd()
            XCTAssertTrue(ScheduleManager.sharedInstance. addMethodCalled)
        }
    }
    

提交回复
热议问题