如何覆盖 XCTest 中的表视图委托
How to override tableview delegate in XCTest
如何为这个 "success" 场景编写测试用例?
if ([tblView.delegate respondsToSelector:@selector(tableView:viewForHeaderInSection:)]) {
...
}else{
...
}
我尝试在 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()
}
}
代码:
mockTableView.delegate=MockTableViewDelegate()
print("delegate===\(mockTableView.delegate)")
它打印 nil。我为数据源尝试过相同的模型,它正在返回数据源 obj。为什么委托返回零?以及如何测试这种情况?
委托通常是弱引用。如果您首先将 MockTableViewDelegate
分配给一个局部变量,它在 print
中使用时应该仍然存在。请尝试以下操作:
let delegate = MockTableViewDelegate()
mockTableView.delegate = delegate
print("delegate===\(mockTableView.delegate)")
print(delegate)
需要第四行才能使第三行的对象存活。
最后我发现这是 iOS 运行时中的错误。解决此问题的一种方法是使用 OCMock,但它不适用于 Swift。所以我现在写在Objective-c。
UITableView *tableView = [[UITableView alloc]init];
UIView *headerView = [UIView new];
id delegateProtocolMock = OCMProtocolMock(@protocol(UITableViewDelegate));
tableView.delegate=delegateProtocolMock;
OCMStub([delegateProtocolMock tableView:tableView viewForHeaderInSection:0]).andReturn(headerView);
如何为这个 "success" 场景编写测试用例?
if ([tblView.delegate respondsToSelector:@selector(tableView:viewForHeaderInSection:)]) {
...
}else{
...
}
我尝试在 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()
}
}
代码:
mockTableView.delegate=MockTableViewDelegate()
print("delegate===\(mockTableView.delegate)")
它打印 nil。我为数据源尝试过相同的模型,它正在返回数据源 obj。为什么委托返回零?以及如何测试这种情况?
委托通常是弱引用。如果您首先将 MockTableViewDelegate
分配给一个局部变量,它在 print
中使用时应该仍然存在。请尝试以下操作:
let delegate = MockTableViewDelegate()
mockTableView.delegate = delegate
print("delegate===\(mockTableView.delegate)")
print(delegate)
需要第四行才能使第三行的对象存活。
最后我发现这是 iOS 运行时中的错误。解决此问题的一种方法是使用 OCMock,但它不适用于 Swift。所以我现在写在Objective-c。
UITableView *tableView = [[UITableView alloc]init];
UIView *headerView = [UIView new];
id delegateProtocolMock = OCMProtocolMock(@protocol(UITableViewDelegate));
tableView.delegate=delegateProtocolMock;
OCMStub([delegateProtocolMock tableView:tableView viewForHeaderInSection:0]).andReturn(headerView);