As far as I know there is no possible solution for mocking and stubbing methods in swift like we were used in objc with OCMock, Mockito, etc.
I'm aware of technique described here. It is quite useful in some cases, but now I had a deadlock :)
I had a service layer where I had something like contracts(calling this method with this params will return that object as callback). This is one(greatly simplified) example:
class Bar
{
func toData() -> NSData
{
return NSData()
}
}
class Foo
{
class func fromData(data: NSData) -> Foo
{
return Foo()
}
}
class ServerManager
{
let sharedInstance = ServerManager()
class func send(request: NSData, response: (NSData)->())
{
//some networking code unrelated to the problem
response(NSData())
}
}
class MobileService1
{
final class func Contract1(request: Bar, callback: (Foo) -> ())
{
ServerManager.send(request.toData()) { responseData in
callback(Foo.fromData(responseData))
}
}
//Contract2(...), Contract3(...), etc
}
Therefore somewhere in the code I had following scenario:
func someWhereInTheCode(someBool: Bool, someObject: Bar)
{
if someBool
{
MobileService1.Contract1(someObject) { resultFoo in
//self.Foo = resultFoo
}
}
else
{
//MobileService1.Contract2(...)
}
}
And the question now is how the heck could I test this? Is there better(for testing) alternative for code structure without touching contracts themselves?
Better late than never I found a solution. Just make dependency injection of the
MobileService1
(or better of it's interface) and then mock it easily:Now you can easily change service in your tests:
And the best part is with default values you can still call it the old way(not braking change):