为什么叫“虚假”?因为有时候真实的东西风险太大。
databaseSaver.save() // real records, yikes!
requestMaker.makeRequest() // pound that server!
rainMaker.makeRain() // goodness no!
Spurious使得在测试过程中更容易进行存根化和伪造对象依赖。
给定
class FakeRainMaker: RainMaker, SpuriousTestable {
func makeRain() -> String {
// will register any calls with Spurious, identified by String "makeRain()"
return callSpurious()
}
func rainfallTotals(cityName: String, month: Int) -> Int {
// will register any calls with Spurious, identified by String "rainfallTotals(_:month:)"
return callSpurious([cityName, month])
}
}
当
rainMaker = FakeRainMaker()
subject.rainMaker = rainMaker
rainMaker.stub("makeRain()", yield: "Chocolate rain")
非常好。然后(使用Quick匹配器)
let rain = subject.precipitation()
expect(rainMaker.wasCalled("makeRain()")).to(beTruthy())
expect(rain) == "Chocolate rain"
使用Swift 2的能力为协议提供默认实现,可以声明特定类或协议的实例也实现协议SpuriousTestable,并且会自动获得通过Spurious实例注册存根和验证函数调用的能力。
更多…
rainMaker.stub("rainfallTotals(_:month:)", yield: 5555)
let totalInches = subject.getLocalRainLastJanuary()
expect(rainMaker.wasCalled("rainfallTotals(_:month:)", <-"UserCity", <-1)) == true
// can also be written as:
expect(rainMaker.wasCalled("rainfallTotals(_:month:)", with("UserCity"), and(1))) == true
expect(totalInches) == 5555
要运行示例项目,请克隆仓库,然后先从示例目录运行pod install
Swift 2.0
Spurious通过CocoaPods提供。要安装,只需将以下行添加到您的Podfile中:
pod "Spurious"
Justin Wilkey
Spurious可在MIT许可下使用。有关更多信息,请参阅LICENSE文件。