You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

测试时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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.01 19:59:49