我只从TestClass调用了undoMethod一次。但undo方法执行registerUndo的次数。
这是我的测试类。
import XCTest
@testable import UnitTestProject
class UnitTestProjectTests: XCTestCase {
func testUndo() {
let model = TestModel()
model.increment()
XCTAssertEqual(model.count, 1)
model.increment()
XCTAssertEqual(model.count, 2)
model.increment()
XCTAssertEqual(model.count, 3)
model.undo()
XCTAssertEqual(model.count, 2)
}
}这是目标类。
import Foundation
class TestModel {
let undoManager = UndoManager()
var count = 0
func registerUndo() {
if (undoManager.isUndoRegistrationEnabled) {
undoManager.registerUndo(withTarget: self, handler: { _ in
print("undo is executed")
self.count -= 1
})
}
}
func increment() {
count += 1
registerUndo()
}
func undo() {
if(undoManager.canUndo){
undoManager.undo()
}
}
}如您所见,这个测试代码只调用了undo方法一次。但是undo方法实际上调用了三次,所以这个测试将会失败。
this is console log
Test Case '-[UnitTestProjectTests.UnitTestProjectTests testUndo]' started.
undo is executed
undo is executed
undo is executed
/Users/project/UnitTestProject/UnitTestProjectTests/UnitTestProjectTests.swift:27: error: -[UnitTestProjectTests.UnitTestProjectTests testUndo] : XCTAssertEqual failed: ("0") is not equal to ("2")
Test Case '-[UnitTestProjectTests.UnitTestProjectTests testUndo]' failed (0.019 seconds).
Test Suite 'UnitTestProjectTests' failed at 2021-01-04 22:21:43.585.
Executed 1 test, with 1 failure (0 unexpected) in 0.019 (0.020) seconds
Test Suite 'UnitTestProjectTests.xctest' failed at 2021-01-04 22:21:43.585.
Executed 1 test, with 1 failure (0 unexpected) in 0.019 (0.021) seconds
Test Suite 'Selected tests' failed at 2021-01-04 22:21:43.586.
Executed 1 test, with 1 failure (0 unexpected) in 0.019 (0.023) seconds我想问以下两点。
·为什么这个undo方法在测试时多次执行registerUndo?
·如何测试这样的Undo和Redo方法?
最后,感谢你对这个问题的思考,这个问题是用糟糕的英语写的。
发布于 2021-01-05 01:14:55
默认情况下,undoManager对在同一运行循环周期内执行的所有操作进行分组。在您的示例中,您将执行三个连续的操作,因此这三个操作构成了undoManager堆栈中的一个组。在撤消时,这三个操作一次被还原,这就是为什么您会看到处理程序块被调用三次而不是一次。
您可以更改默认行为,但代价是自己管理分组,因为任何操作,即使是单个操作,都必须包含在一个组中。我给你一个例子,但请考虑到,我是一个objective-c用户,没有练习swift (幸运的是,这里的语法非常简单)。
首先,您应该停用默认行为,即自动对操作进行分组:
undoManager.setGroupByEvent = NO然后,每个对registerUndo的调用都应该包含一个对beginUndoGrouping和endUndoGrouping的调用(可以使用专用函数来简化):
undoManager.beginUndoGrouping
undoManager.registerUndo(withTarget: self, handler: { _ in
print("undo is executed")
self.count -= 1
})
undoManager.endUndoGrouping现在,您必须调用undo三次才能获得与示例中相同的结果,并且您应该能够更简单地分解测试。
https://stackoverflow.com/questions/65563546
复制相似问题