SkillAgentSearch skills...

DelegatePatternExample

A Delegate Pattern Example With Unit Tests

Install / Use

/learn @iosharry/DelegatePatternExample
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

DelegatePatternExample

A Delegate Pattern Example With Unit Tests

[Production Code]

Protocol Design

protocol SwitchableTableViewCellDelegate: class {
    func valueChanged(_ isOn: Bool)
}

Adopt the protocol

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: SwitchableTableViewCell.cellId, for: indexPath) as? SwitchableTableViewCell else { return UITableViewCell() }
		
    cell.delegate = self
		
    return cell
}

Implementation of the adopted protocol

extension ViewController: SwitchableTableViewCellDelegate {
    func valueChanged(_ isOn: Bool) {
        titleLabel.text = "Switch isOn -> \(isOn)"
    }
}

Stored protocol property & Event

weak var delegate: SwitchableTableViewCellDelegate?

@IBAction func valueChangedSwitch(_ sender: UISwitch) {
    delegate?.valueChanged(sender.isOn)
}

[Unit Test]

Protocol Mocking

class MockSwitchableTableViewCellDelegate: SwitchableTableViewCellDelegate {
    var valueChangedCallCount = 0
	
    func valueChanged(_ isOn: Bool) {
        valueChangedCallCount += 1
    }
}


Dependency injection UITableViewCell

let mockDelegate = MockSwitchableTableViewCellDelegate()
cell.delegate = mockDelegate

Event Test

func testSwitchableDelegate_whenValueChanged_isOn() {
    // given
    let mockDelegate = MockSwitchableTableViewCellDelegate()
    cell.delegate = mockDelegate
		
    // when
    cell.switch.sendActions(for: .valueChanged)
		
    // then
    XCTAssertEqual(mockDelegate.valueChangedCallCount, 1)
}
View on GitHub
GitHub Stars5
CategoryDevelopment
Updated1y ago
Forks0

Languages

Swift

Security Score

55/100

Audited on Apr 11, 2024

No findings