在 Swift 中从模拟调用 super
Calling super from a mock in Swift
我正在关注 Swift 中的一个模拟示例,它在调用我们正在测试的函数时将变量设置为 true,但我不清楚的是,我们似乎重写了该函数在模拟的 subclass 中,然后我们 return 它的 parent 方法的再现。我假设覆盖的工作方式是我们用我们想要的逻辑重写函数,当我们这样做时我假设 parent class 容纳原始函数完全不知道 child class处理函数?
示例代码如下:
extension ItemListDataProviderTests{
class MockTableView: UITableView {
var cellGotDequeued = false
override func dequeueReusableCell(withIdentifier identifier: String, for indexPath: IndexPath) -> UITableViewCell {
cellGotDequeued = true
return super.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
}
}
returning parent 方法如何调用覆盖函数并将测试变量设置为 true?我假设通过调用 super 它将 运行 parent 的逻辑而不触发 child 的覆盖方法。
您展示的方法
- 将
cellGotDequeued
设置为 true
- 调用父 class' 实现
dequeueReusableCell
- returns 从父 class 实现返回的 结果 (不是 "parent's rendition of the method")
您是正确的,父 class 不知道子 class 是如何覆盖此方法的。
调用 super
确实会调用父 class' 实现,但会在子 classes 实现期间调用,并且绝不会阻止子实现的执行。子 class 对 super
的使用决定了是否应该调用父实现,如果是,是否应该在之前或之后执行任何其他操作。
我正在关注 Swift 中的一个模拟示例,它在调用我们正在测试的函数时将变量设置为 true,但我不清楚的是,我们似乎重写了该函数在模拟的 subclass 中,然后我们 return 它的 parent 方法的再现。我假设覆盖的工作方式是我们用我们想要的逻辑重写函数,当我们这样做时我假设 parent class 容纳原始函数完全不知道 child class处理函数?
示例代码如下:
extension ItemListDataProviderTests{
class MockTableView: UITableView {
var cellGotDequeued = false
override func dequeueReusableCell(withIdentifier identifier: String, for indexPath: IndexPath) -> UITableViewCell {
cellGotDequeued = true
return super.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
}
}
returning parent 方法如何调用覆盖函数并将测试变量设置为 true?我假设通过调用 super 它将 运行 parent 的逻辑而不触发 child 的覆盖方法。
您展示的方法
- 将
cellGotDequeued
设置为true
- 调用父 class' 实现
dequeueReusableCell
- returns 从父 class 实现返回的 结果 (不是 "parent's rendition of the method")
您是正确的,父 class 不知道子 class 是如何覆盖此方法的。
调用 super
确实会调用父 class' 实现,但会在子 classes 实现期间调用,并且绝不会阻止子实现的执行。子 class 对 super
的使用决定了是否应该调用父实现,如果是,是否应该在之前或之后执行任何其他操作。