Swift-如何使用通用测试?

发布于 2025-02-12 20:16:22 字数 930 浏览 1 评论 0原文

我想与仿制药一样 但是我想不出一种方式。

我的代码如下,我想测试零件准备()

class A_ViewModel {
    var useCase: UseCaseProtocol = UseCase()
    var item: A_CellModel = .init()
    
    // I want to unittest prepare()
    func prepare() {
        // logic....
        
        // and call calcuate
        useCase.calculate(item: item)
    }
}

protocol TestableProtocol {
    var testProperty: Bool { get set }
}

class A_CellModel: TestableProtocol {
    var testProperty: Bool = false
}

protocol UseCaseProtocol {
    func calculate<T: TestableProtocol>(item: T)
}

class UseCase: UseCaseProtocol {
    func calculate<T: TestableProtocol>(item: T) {
        // logic......
    }
}

但是,由于calcaulte(item:)在USECase中使用通用,因此有必要移交清晰的类型(A_CELLMODEL)。

在这种情况下,A_ViewModel和A_CellModel之间存在依赖性,这使得很难测试该单元。

为了测试准备()carcaulte(item:)放弃通用吗? 我应该使用存在类型吗?

I wanna unittest with generics.
But I can't think of a way.

My code is as below, and I want to test the part prepare().

class A_ViewModel {
    var useCase: UseCaseProtocol = UseCase()
    var item: A_CellModel = .init()
    
    // I want to unittest prepare()
    func prepare() {
        // logic....
        
        // and call calcuate
        useCase.calculate(item: item)
    }
}

protocol TestableProtocol {
    var testProperty: Bool { get set }
}

class A_CellModel: TestableProtocol {
    var testProperty: Bool = false
}

protocol UseCaseProtocol {
    func calculate<T: TestableProtocol>(item: T)
}

class UseCase: UseCaseProtocol {
    func calculate<T: TestableProtocol>(item: T) {
        // logic......
    }
}

However, since calcaulte(item:) in usecase uses generic, it is necessary to hand over the clear type (A_CellModel).

In that case, there is a dependence between A_ViewModel and A_CellModel, which makes it difficult to test the unit.

In order to test prepare(), should calcaulte(item:) give up generic?
Should I use existential type?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文