我遇到一些UT的问题我试图用swift
写我有一个扩展程序的协议,"做东西" :
protocol MyProtocol: class
{
var myVar: SomeClass { get }
func doStuff(identifier: String) -> Bool
}
extension MyProtocol
{
func doStuff(identifier: String) -> Bool {
return true
}
}
然后是一个实现我的协议的类
final class MyClass: MyProtocol {
}
这个类有一个扩展,它实现了一个其他协议,它有一个我应该测试的方法
public protocol MyOtherProtocol: class {
func methodToTest() -> Bool
}
extension MyClass: MyOtherProtocol {
public func methodToTest() {
if doStuff() {
return doSomething()
}
}
}
这种设置有没有办法模拟doStuff方法?
答案 0 :(得分:3)
最好是解决协议而不是类。因此,您可以扩展协议
,而不是扩展您的课程extension MyOtherProtocol where Self: MyProtocol {
public func methodToTest() {
if doStuff() {
return doSomething()
}
}
}
所以你的扩展会知道,doStuff存在,但不知道它的实现 然后让你的课程符合两者。
extension MyClass: MyOtherProtocol {}
所以在模拟中你可以实现
class MyMockClass: MyProtocol, MyOtherProtocol {
func doStuff() -> Bool {
return true
}
}