Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift extensions and Unit Tests

Tags:

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 ?

like image 375
AnderCover Avatar asked Jan 08 '18 10:01

AnderCover


People also ask

What are unit tests Swift?

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.

What are extensions used for in Swift?

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.

What is difference between unit tests and UI test in Xcode?

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.


1 Answers

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
    }
}
like image 71
MichaelV Avatar answered Sep 22 '22 12:09

MichaelV