lundi 4 janvier 2021

undo method of UndoManager execute number of times the registerUndo while testing

I called undoMethod from the TestClass only once. But undo method executed number of times the registerUndo.

this is my test class.

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)
        
    }
}

and this is target class.

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()
        }
    }
}

as you can see, this test code called undo method only once. But undo method actually called three times, so this test will fail.

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

I would like to ask the following 2 points.

・Why this undo method executed number of times the registerUndo while testing?

・How to test Undo and Redo method like this?

Finally, thank you for your thinking for this question what written in poor English.

Aucun commentaire:

Enregistrer un commentaire