gpt4 book ai didi

swift - 在swift中将可测试代码与静态方法调度结合起来

转载 作者:行者123 更新时间:2023-11-28 11:43:16 25 4
gpt4 key购买 nike

我最近阅读了很多有关 Swift 运行时的文章,并且对使用静态方法分派(dispatch)优化我的代码越来越感兴趣。这发生在以下方法中:

  • 结构方法
  • final 类方法,即用 final 关键字声明为私有(private)或在 final 类中
  • 在协议(protocol)扩展中定义的协议(protocol)方法,但未在协议(protocol)本身中声明。

问题是,这些情况都不能让我编写可测试的代码,至少不是我现在这样做的方式:注入(inject)在单元测试中被模拟替换的协议(protocol)实体。

那么,是否有可能在不放弃静态方法分派(dispatch)的情况下编写可测试的代码,如果可以的话,应该怎么做呢?

谢谢!

最佳答案

泛型正是您要寻找的。您可以对协议(protocol)进行抽象,但编译器仍然知道您使用的确切类型,因此不需要动态调度。

protocol Dependency {
func doSomething()
}

struct RealDependency: Dependency {
func doSomething() {
print("I'm doing real work")
}
}

struct MockDependency: Dependency {
func doSomething() {
print("I'm the mock, so I do nothing")
}
}

struct MyApp<D: Dependency> {
let dependency: D

func doSomething() {
dependency.doSomething()
}
}

let myAppReal = MyApp(dependency: RealDependency())
let myAppMock = MyApp(dependency: MockDependency())

myAppReal.doSomething() // Prints "I'm doing real work"
myAppMock.doSomething() // Prints "I'm the mock, so I do nothing"

但是请注意,在 Swift 中,不能保证泛型单态化。因此,您可能无论如何都会以某种形式的动态调度结束。参见 this link

关于swift - 在swift中将可测试代码与静态方法调度结合起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53180010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com