SaRaVaNaN D SaRaVaNaN D - 2 years ago 193
Swift Question

How to override tableview delegate in XCTest

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

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

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



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?

Answer Source

Finally i found this is a bug in the iOS runtime. The one way to solve this problem is to use OCMock, but its not available for Swift. So I have written in Objective-c for now.

UITableView *tableView = [[UITableView alloc]init];
UIView *headerView = [UIView new];

id delegateProtocolMock = OCMProtocolMock(@protocol(UITableViewDelegate));
OCMStub([delegateProtocolMock tableView:tableView viewForHeaderInSection:0]).andReturn(headerView);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download