1

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.

Amogam
  • 321
  • 5
  • 20
  • You should define more about what are you testing for? API testing, logic testing, etc... Protocol can do many things :) – son Mar 01 '21 at 09:46
  • some returns an image for assets , some shows toast etc.. – Amogam Mar 01 '21 at 13:04

1 Answers1

4

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))
}
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
  • There are lots of protocol in the project and it decreases the unit test coverage. Is there any way to exclude protocols and some other methods from Unit test code coverage ? – Amogam Mar 01 '21 at 12:41
  • 1
    @Amogam No a protocol doesn't decrease the coverage value. In my example above I will have 100% code coverage because I have a test for the default implementation of `calculate()`, the actual definition `protocol Example {...}` is not being included when calculating code coverage. – Joakim Danielson Mar 01 '21 at 14:08
  • Thanks for replying. How about Structs and enum files ? are those included in code coverage ? – Amogam Mar 01 '21 at 14:44
  • 1
    structs yes, for enum not the actual `case ...` definitions but any other code you add. – Joakim Danielson Mar 01 '21 at 15:15