And*_*ver 5 unit-testing swift swift-protocols
我有一些 UT 的问题,我正在尝试快速编写
我有一个带有“做事”扩展名的协议:
protocol MyProtocol: class
{
var myVar: SomeClass { get }
func doStuff(identifier: String) -> Bool
}
extension MyProtocol
{
func doStuff(identifier: String) -> Bool {
return true
}
}
Run Code Online (Sandbox Code Playgroud)
然后是一个实现我的协议的类
final class MyClass: MyProtocol {
}
Run Code Online (Sandbox Code Playgroud)
这个类有一个扩展,它实现了另一个协议,它有一个我应该测试的方法
public protocol MyOtherProtocol: class {
func methodToTest() -> Bool
}
extension MyClass: MyOtherProtocol {
public func methodToTest() {
if doStuff() {
return doSomething()
}
}
}
Run Code Online (Sandbox Code Playgroud)
这个设置有没有办法模拟 doStuff 方法?
解决协议而不是类是一个很好的做法。因此,您可以扩展协议,而不是扩展类
extension MyOtherProtocol where Self: MyProtocol {
public func methodToTest() {
if doStuff() {
return doSomething()
}
}
}
Run Code Online (Sandbox Code Playgroud)
所以你的扩展会知道 doStuff 存在,但不知道它的实现。然后让你的类同时符合两者。
extension MyClass: MyOtherProtocol {}
Run Code Online (Sandbox Code Playgroud)
所以在模拟中你可以实现
class MyMockClass: MyProtocol, MyOtherProtocol {
func doStuff() -> Bool {
return true
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2787 次 |
| 最近记录: |