gpt4 book ai didi

swift - 如何在 swift 单元测试中验证方法是否在具体类中被调用

转载 作者:行者123 更新时间:2023-11-30 11:12:07 24 4
gpt4 key购买 nike

我有这样的场景:

class X {
init(y: ProtocolA)

func foo(){
if(y.isSomething()){
methodA()
} else {
methodB()
}
}

func methodA(){
// any
}

func methodB(){
// any
}

}

class Y : ProtocolA {

func isSomething(): Bool { return true OR false }

}

我想测试X级

我将模拟 ProtocolA 在两个不同的测试中返回 isSomething() 方法 true 或 false,以了解 methodA调用了 methodB

解决这个问题的最佳策略是什么?

ps:使用mockito,使用Spyverify,这非常容易,但使用Swift,这非常痛苦

编辑:

好吧,我这样做:

首先,部件:

class X { init(y: Y) }
protocol Y { func isSomething() -> Bool }

现在,测试的结构:模拟 spy 对象

typealias VerifyMethodAssert = (count: Int, parameters: [Any]?, returnn: Any?)

可配置的依赖模拟

class YMock : Y {


init(configure: Bool)
func isSomething{ return configure }

}

具体类的 spy

class XSpy : X {

private let y: Y

var verify: [String: VerifyMethodAssert] = [
"methodA()": (count: 0, parameters: nil, returnn: nil)
"methodB()": (count: 0, parameters: nil, returnn: nil)
]

var nothing: [String: Bool] = [
"methodA()": false
"methodB()": false
]

init(y: Y, verify: [String: VerifyMethodAssert]?, nothing: [String: Bool]?)

func methodA(){
verify["\(#function)"] = (count: verify["\(#function)"]!.count + 1, parameters: nil,
returnn: nothing["\(#function)"]! ? nil : super.methodA())
}

func methodB(doNothing: Bool = false){
verify["\(#function)"] = (count: verify["\(#function)"]!.count + 1, parameters: nil,
returnn: nothing["\(#function)"]! ? nil : super.methodB())
}

}

和测试:

class XTest : QuickSpec {

override func spec(){
describe("a position view model"){

it("test 1"){
let y = Y(configure: true)
let x = XSpy(y: y)

x.foo()

expect(1).to(x.verify["methodA()"].count)
expect(0).to(x.verify["methodB()"].count)
}

it("test 2"){
let y = Y(configure: true)
let x = XSpy(y: y)

x.foo()

expect(0).to(x.verify["methodA()"].count)
expect(1).to(x.verify["methodB()"].count)
}

}
}
}

最佳答案

据我所知,没有开箱即用的方法。一种方法是检查计数器:

class X {

var countA: Int = 0
var countB: Int = 0

init(y: ProtocolA)

func foo(){
if(y.isSomething()){
methodA()
} else {
methodB()
}
}

func methodA(){
countA += 1
// any

}

func methodB(){
countB += 1
// any
}

}

也建议采用这种方法here .

关于swift - 如何在 swift 单元测试中验证方法是否在具体类中被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52081144/

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