Search code examples
iosswiftunit-testingnsundomanager

Default undoManager is nil when testing


I am working on adding some tests to a Swift library which uses undoManager. In the library's demo, adding the following print to viewDidAppear: results in an NSUndoManagerObject being printed.

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    print(undoManager)
}

I wrote another ViewController for the tests, and when I have the same code in the ViewController's viewDidAppear:, nil is printed.

I'm creating the ViewController for the tests with the following code:

override func setUp() {
    super.setUp()

    // Put setup code here. This method is called before the invocation of each test method in the class.
    let storyboard = UIStoryboard(name: "Main", bundle: NSBundle(forClass: self.dynamicType))

    viewController = storyboard.instantiateInitialViewController() as! ViewController
    viewController.viewDidLoad()
    viewController.viewDidAppear(false)

    // Test and Load the View at the Same Time!
    XCTAssertNotNil(viewController.view)
}

I call becomeFirstResponder() inside of the ViewController's viewDidLoad:.

I want to test logic that uses the default undoManager, so I need to figure out why it's nil. I've tried assigning the default undoManager a new instance of NSUndoManager, but it's a read only property.

Here is the Github repository if you're interested in seeing the code.


Solution

  • I wasn't able to get the default undoManager working with testing for this project, but I ended up using the following solution which I think works just as well. In the class that uses the undoManager, I've added a private NSUndoManager variable and then defined it inside of init like so:

    classUndoManager = undoManager
    if classUndoManager == nil {
        classUndoManager = NSUndoManager()
    }
    

    Anywhere that used undoManager now uses classUndoManager.