ios - 默认协议扩展中的方法总是在单元测试中执行
问题描述
我在该协议的扩展中有一个带有默认实现的协议。当我尝试创建该协议的具体模拟对象以进行单元测试时,总是会执行默认实现。我不知道为什么。任何帮助,将不胜感激。我在 xcode 11.3
protocol ABC: AnyObject {
func doSomething()
}
extension ABC {
func doSomething() {
print("Did Something")
}
}
final class ClassToBeTested {
var abc: ABC?
func methodToBeTested() {
abc?.doSomething()
}
}
在测试目标
final class MockABC: ABC {
func doSomething() {
print("Did Something in Test Target")
}
}
final class Tests: XCTestCase {
func testMethod() {
let obj = ClassTobeTested()
// abc property is of type protocol ABC
obj.abc = MockABC()
*This line calls the default implementation of the protocol of ABC and not the
implementation in MockABC class - verifiable by breakpoints and print statements*
obj.methodToBeTested()
}
}
我已经阅读了static
在这种情况下发生的调度,但找不到任何特殊原因。请帮忙。
解决方案
您需要注入协议。
protocol ABC: AnyObject {
func doSomething() -> String
}
extension ABC {
func doSomething() -> String {
return "Did Something"
}
}
final class ClassToBeTested {
private let abc: ABC
init(abc: ABC) {
self.abc = abc
}
func methodToBeTested() -> String {
return abc.doSomething()
}
}
测试目标
final class ABCMock: ABC {
func doSomething() {
print("Did Something in Test Target")
}
}
final class ClassToBeTestedTests: XCTestCase {
private let mockABC: MockABC = .init()
func test_methodToBeTested() {
let obj = ClassTobeTested()
XCTAssertEqual(obj.methodToBeTested(), "Did Something in Test Target")
}
}
这段代码非常简单,但根据您的问题,这是最好的方法。
推荐阅读
- java - 在生产环境中管理 SSL 证书(Spring 应用程序)
- python - 你能 ping SQL Server 并请求知道它需要连接什么驱动程序吗?
- c# - 集成测试未从 App.Config 文件中读取
- x86-64 - 在 CGo 中确定环境是否支持 AVX-512 的正确方法是什么?
- python - Django Rest 框架视图集计数外键
- c# - 是否可以向 C# 中的现有方法或类添加更多文档?
- linux - 如果不存在原子如何打开或创建目录
- python - Python; 电报机器人;两个文件
- node.js - 如何在 chrome 94 中使用 selenium-webdriver?
- sql - Oracle 使用 REGEXP 从一列中获取所有匹配项