Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override tableview delegate in XCTest

How to write a testcase for this "success" scenario?

if ([tblView.delegate respondsToSelector:@selector(tableView:viewForHeaderInSection:)]) {
         ...
}else{
         ...
}

I have tried by creating the below mock delegate in swift:

class MockTableViewDelegate:NSObject, UITableViewDelegate {

  @objc func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
            return 30
        }

        // MARK: Delegates
   @objc func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
            return UIView()
        }
}

Code:

mockTableView.delegate=MockTableViewDelegate()  
print("delegate===\(mockTableView.delegate)")

It prints nil. The same mockup I have tried for the datasource and it is returning the datasource obj. Why delegate is returning nil? and how to test this scenario?

like image 217
SaRaVaNaN DM Avatar asked Dec 12 '25 21:12

SaRaVaNaN DM


1 Answers

Delegates are usually weak references. If you assign your MockTableViewDelegate to a local variable first it should still be alive when used in print. Try the following:

let delegate = MockTableViewDelegate()
mockTableView.delegate = delegate
print("delegate===\(mockTableView.delegate)")
print(delegate)

The fourth line is required to keep the object living for the third line.

like image 178
0x52 Avatar answered Dec 15 '25 13:12

0x52



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!