Why is undoManager of NSTextView subclass always nil when testing?

18 hours ago 1
ARTICLE AD BOX

I have a subclass (MyTextView) of NSTextView. When i try to test its (working) undo/redo using Swift Testing its undoManager property is always niland the test fails.

// Added extension extension MyTextView { override var undoManager: UndoManager? { _testingUndoManager } } @MainActor struct Undo { let mtv: MyTextView init() throws { mtv = MyTextView() mtv.insertText("Lorem ipsum dolor sit amet") mtv._testingUndoManager = UndoManager() // <-- Added mtv.moveToBeginningOfDocument(self) mtv.moveWordRightAndModifySelection(self) } @Test func roundtrip() async throws { #expect(mtv.selections == [(0, 5)]) mtv.delete(self) #expect(mtv.selections == [(0, 0)]) #expect(mtv.allowsUndo) mtv.undoManager?.undo() // undoManager is always nil #expect(mtv.selections == [(0, 5)]) let strings = mtv.getSelectedText() #expect(strings == ["Lorem"]) } }

Apparently the full machinery (run loop?) is not set up by the test. Is there some way force the instantiation of an undo manager during testing?

Edit: I've updated the code above with the only solution I've found so far in case anyone comes across the same situation in the future. It unfortunately requires adding an instance variable to the NSTextView subclass:

var _testingUndoManager: UndoManager? = nil
Read Entire Article