Search code examples
iosswiftnsfetchedresultscontrollerxctest

How do I unit test NSFetchedResultsControllerDelegate (controllerWillChangeContent and controllerDidChangeContent) using Swift


I have the following delegate and I need to test that tableView.beginUpdates() got called. I'm using XCTest and Swift 3. Do you have any ideas or sample code?

extension SomeListController: NSFetchedResultsControllerDelegate {



func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {

    tableView.beginUpdates()

}



func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {

    tableView.endUpdates()

}

}


Solution

  • I actually figured it out eventually. The endsUpdates test is pretty much the same pattern.

    func test_controllerWillChangeContent_beginsUpdates() {
    
        class MockTableView: UITableView {
    
            var gotCalled: Bool = false
            override func beginUpdates() {
                gotCalled = true
            }
    
        }
    
        let tableView: MockTableView = MockTableView()
        controller.tableView = tableView
    
        let _ = controller.view
    
        controller.controllerWillChangeContent(controller.fetchedResultsControler as! NSFetchedResultsController<NSFetchRequestResult>)
    
        XCTAssertTrue(tableView.gotCalled)
    
    }