测试时NSTextView子类的undoManager为何始终为nil?
问题:NSTextView子类测试时UndoManager始终为nil的解决办法
我有一个NSTextView的子类MyTextView,使用Swift Testing测试其正常工作的撤销/重做功能时,它的undoManager属性始终为nil,导致测试失败。
测试代码如下:
// 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"]) } }
显然测试环境未搭建完整机制(比如运行循环?),请问是否有办法在测试时强制实例化undoManager?
编辑: 我已更新上述代码,附上目前找到的唯一解决方案,供遇到相同问题的开发者参考。遗憾的是,这需要给NSTextView子类添加一个实例变量:
var _testingUndoManager: UndoManager? = nil
内容的提问来源于stack exchange,提问作者user1007047
相关产品推荐
相关产品推荐

