如何在 swift 中测试闭包

How to test closures in swift

我是编写测试用例的新手,所以请不要拒绝任何建议。

问题 - 我如何为(闭包/高阶函数)而不是 api 调用闭包(不包括它们)编写测试用例, 为了获得 100% 的覆盖率,我只停留在这部分。

代码 -

init () {
    
   

    var items:[ReturnPaymentsOptionsModel] = []
    items.append(ReturnPaymentsOptionsModel(text: "Unexpected payment or \nunknown sender", isSelected: false))
    items.append(ReturnPaymentsOptionsModel(text: "Incorrect currency", isSelected: false))
    items.append(ReturnPaymentsOptionsModel(text: "Incorrect amount", isSelected: false))
    items.append(ReturnPaymentsOptionsModel(text: "Duplicate", isSelected: false))
    items.append(ReturnPaymentsOptionsModel(text: "Auction/Order cancelled", isSelected: false))
    items.append(ReturnPaymentsOptionsModel(text: "Charges exceeds the principle amount", isSelected: false))

    let observableToggleItems = Observable.just(items)
    
    let tappedItemAction = Observable.combineLatest(observableToggleItems, itemTapped)
        .map { argument -> [ReturnPaymentsOptionsModel] in // for this  closure im stuck
            
            let (items, indexPath) = argument
            var modifiedItems = items
            
            for index in modifiedItems.indices {
                
                if index == indexPath.row {
                    modifiedItems[index].isSelected.toggle()
                } else {
                    modifiedItems[index].isSelected = false
                }
            }
            
            return modifiedItems
        }.startWith(items)
    
    didFetchToggleItems = Observable.merge(getToggleItems.withLatestFrom(observableToggleItems), tappedItemAction)
}

我假设您在这里测试 Rx 链没有问题,但闭包本身没有问题。

那么如果你将整个闭包提取到一个函数中会更好,你可以直接进行单元测试,然后只需在 .map 中调用闭包中的函数,例如:

function modifyItems(argument: ([Item], IndexPath)) -> [ITTReturnPaymentsOptionsModel] {
    // Your closure here
}

然后是这样的:

let tappedItemAction = Observable.combineLatest(observableToggleItems, itemTapped)
        .map { modifyItems([=11=]) }
        .startWith(items)

这将允许您独立于 Rx 链对函数进行单元测试。