Search code examples
swiftunit-testingprotocolsswift-protocolsprotocol-extension

How do I unit test Protocol and it's extension


I have a protocol and I have it's definition in extension.

I'd like to unit test the definition.

I googled but I couldn't find anything relevant.

The closest one I get is Mocking with Protocol or POP etc..

If someone could explain me with a sample , it'd be great.


Solution

  • There is no need to unit test the protocol themselves, you should test the conforming types. If you have a protocol extension with some default behaviour you want to test then create some basic struct or class in your test target that conforms to the protocol and use it in your tests.

    Here is an example, given the below protocol with a function and a default implementation for that function

    protocol Example {
        func calculate(_ x: Int) -> Int
    }
    
    extension Example {
        func calculate(_ x: Int) -> Int {
            x * 2
        }
    } 
    

    you can add a simple struct in your test target for testing this, since we want to test the default implementation the struct becomes very simple

    struct TestExample: Example {}
    

    And then a unit test for this could look like

    func testDefaultCalculation() {
        let sut = TestExample()
        XCTAssertEqual(2, sut.calculate(1))
    }