gpt4 book ai didi

swift - 模拟并注入(inject) ObservableObject

转载 作者:行者123 更新时间:2023-12-04 13:38:19 26 4
gpt4 key购买 nike

我有一个类FooObservableObject 具有多个依赖项.出于测试目的,我想创建这些对象的模拟版本,但我看不到这样做的方法,然后将它们注入(inject) Foo .

  • 我无法创建另一个协议(protocol),我的 ObservableObject实现是因为 ObservableObject协议(protocol)具有自身或关联的类型要求,不能用作声明的类型和
  • 我不能子类化 ObservableObject因为它有 @Published无法覆盖的属性包装成员。
  • 最佳答案

    目前我看到的唯一方法是编写一个订阅 ObservableObject 的模拟订阅者。 :

    final class SomeState: ObservableObject {
    @Published var someValue: String?
    }

    如果 ObservableObject看起来像这样你可以像这样实现模拟订阅者(我称他们为 Watcher ):
    final class SomeStateWatcher {
    let someState: SomeState

    var didSetSomeValue: Bool = false
    var lastSomeValue: String?

    private var someValueSubscriber: AnyCancellable?

    init(someState: SomeState) {
    self.someState = someState

    self.someValueSubscriber = self.someState.$someValue
    .sink(receiveValue: { value in
    self.didSetSomeValue = true
    self.lastSomeValue = value
    })
    }
    }

    func testDoStuffThatChangesTheLocalSomeStateProperty() {
    someImplementation.doStuffThatChangesTheLocalSomeStateProperty(with: "Fourty2")

    XCTAssertTrue(someStateWatcher.didSetSomeValue, "It should have published someValue")
    XCTAssertEqual(someStateWatcher.lastSomeValue, "Fourty2", "It should have published the correct value)
    }

    关于swift - 模拟并注入(inject) ObservableObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60525159/

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