I have a issue with some UT I'm trying to write in swift
I have a protocol with an extension that "does stuff" :
protocol MyProtocol: class
{
var myVar: SomeClass { get }
func doStuff(identifier: String) -> Bool
}
extension MyProtocol
{
func doStuff(identifier: String) -> Bool {
return true
}
}
And then a class that implements my protocol
final class MyClass: MyProtocol {
}
And this class has an extension that implements an other protocol which have a method I'm supposed to test
public protocol MyOtherProtocol: class {
func methodToTest() -> Bool
}
extension MyClass: MyOtherProtocol {
public func methodToTest() {
if doStuff() {
return doSomething()
}
}
}
Is there a way with this setup to mock doStuff method ?
A unit test is a function you write that tests something about your app. A good unit test is small. It tests just one thing in isolation. For example, if your app adds up the total amount of time your user spent doing something, you might write a test to check if this total is correct.
An extension can be used to extend an existing generic type, as described in Extending a Generic Type. You can also extend a generic type to conditionally add functionality, as described in Extensions with a Generic Where Clause.
While unit testing seeks to create a rapid and regular feedback loop for developers to gain confidence in correctness of the code, UI testing validates the application as a whole from an end user's perspective to ensure that the final product performs as expected by users.
It is a good practice to address Protocols instead of Classes. So instead of extending you class you can extend protocol
extension MyOtherProtocol where Self: MyProtocol {
public func methodToTest() {
if doStuff() {
return doSomething()
}
}
}
So your extension will aware, that doStuff exists, but not aware about its implementation. And then make you class conforms to both.
extension MyClass: MyOtherProtocol {}
So in mock you can implement
class MyMockClass: MyProtocol, MyOtherProtocol {
func doStuff() -> Bool {
return true
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With