swift - 即使在 XCTest 文件中的类扩展中实现了方法之后,协议(protocol)的默认实现也始终会被调用

标签 swift mocking protocols xctest

我有一个协议(protocol)

protocol SomeProtocol { func method() }

及其实现

extension SomeProtocol {func method(){--implementation--}}

在构建目标中,我有一个类确认此协议(protocol)

class SomeClass: SomeProtocol { func doSomething() { method() } }

我想要的是我想要在我的测试目标中的 XCTest 文件中对协议(protocol)方法进行不同的实现。为此,我所做的是扩展 SomeClass 并在那里编写我的实现。

extension SomeClass {func method(){--other implementation--} }

但在执行测试用例时它从未被调用。始终会调用构建目标中的方法(默认实现)。

请告诉我应该做什么。

最佳答案

找到了。我使用的是 @testable import MYProject。 如果您使用此方法,则上述方法将不起作用。如果您要添加所有项目文件而不是使用导入,则上述方法有效。

引用:https://medium.com/@hartwellalex/protocol-extensions-and-shared-dependency-injection-in-swift-an-alternative-to-singletons-68934dee6998

关于swift - 即使在 XCTest 文件中的类扩展中实现了方法之后,协议(protocol)的默认实现也始终会被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49521742/

相关文章:

java - csv 阅读器的 mockito 和单元测试

ios - 我无法将 TableViewCell 按钮连接到 TableViewController!如何将值从 TableViewCell 连接到 TableViewController?

swift - 将 UIScroll 和 UIPageControl 从 Objective C 翻译成 swift

sockets - Swift 套接字服务器

java - 如何使用 PowerMockito 模拟私有(private)静态方法?

CLojure:高阶函数 vs 协议(protocol) vs 多方法

swift - 使用 RxSwift 的通用转换方法的问题

go - 来自多个测试用例的类似 sqlmock 期望导致 false 失败

ios - NSURLProtocol canInitWithRequest 调用 5 次

ios - 传递一个 Swift 类作为参数,然后从中调用一个类方法