即使在 XCTest 文件中的 class 扩展中实现方法后,协议的默认实现也会被调用

Always the default implementation of protocol gets called even after implementing the method in class extension in an XCTest file

我有协议

protocol SomeProtocol { func method() }

及其实现

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

在构建目标中,我有一个 class 确认此协议

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

我想要的是在我的 XCTest 文件中的测试目标中有不同的协议方法实现。为此,我所做的是扩展 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