Swift 扩展和单元测试
Swift extensions and Unit Tests
我在 swift
中尝试编写的一些 UT 有问题
我有一个扩展名为 "does stuff" 的协议:
protocol MyProtocol: class
{
var myVar: SomeClass { get }
func doStuff(identifier: String) -> Bool
}
extension MyProtocol
{
func doStuff(identifier: String) -> Bool {
return true
}
}
然后是实现我的协议的 class
final class MyClass: MyProtocol {
}
并且这个 class 有一个扩展实现了另一个协议,它有一个我应该测试的方法
public protocol MyOtherProtocol: class {
func methodToTest() -> Bool
}
extension MyClass: MyOtherProtocol {
public func methodToTest() {
if doStuff() {
return doSomething()
}
}
}
有没有办法用这个设置来模拟 doStuff 方法?
使用协议而不是 类 是一种很好的做法。因此,您可以扩展协议
而不是扩展您 class
extension MyOtherProtocol where Self: MyProtocol {
public func methodToTest() {
if doStuff() {
return doSomething()
}
}
}
所以您的扩展会知道 doStuff 存在,但不知道它的实现。然后让你 class 符合两者。
extension MyClass: MyOtherProtocol {}
所以在模拟中你可以实现
class MyMockClass: MyProtocol, MyOtherProtocol {
func doStuff() -> Bool {
return true
}
}
我在 swift
中尝试编写的一些 UT 有问题我有一个扩展名为 "does stuff" 的协议:
protocol MyProtocol: class
{
var myVar: SomeClass { get }
func doStuff(identifier: String) -> Bool
}
extension MyProtocol
{
func doStuff(identifier: String) -> Bool {
return true
}
}
然后是实现我的协议的 class
final class MyClass: MyProtocol {
}
并且这个 class 有一个扩展实现了另一个协议,它有一个我应该测试的方法
public protocol MyOtherProtocol: class {
func methodToTest() -> Bool
}
extension MyClass: MyOtherProtocol {
public func methodToTest() {
if doStuff() {
return doSomething()
}
}
}
有没有办法用这个设置来模拟 doStuff 方法?
使用协议而不是 类 是一种很好的做法。因此,您可以扩展协议
而不是扩展您 classextension MyOtherProtocol where Self: MyProtocol {
public func methodToTest() {
if doStuff() {
return doSomething()
}
}
}
所以您的扩展会知道 doStuff 存在,但不知道它的实现。然后让你 class 符合两者。
extension MyClass: MyOtherProtocol {}
所以在模拟中你可以实现
class MyMockClass: MyProtocol, MyOtherProtocol {
func doStuff() -> Bool {
return true
}
}