'Swift: Unit testing delegate methods with 3rd party class as an argument

I know how to unit test with 3rd party dependencies by extending the class with your own protocol so that you can inject a mock dependency that implements that same protocol.

But this only seems to work if the 3rd party dependency doesn't make use of the delegate pattern, as the delegate methods tend to have arguments that have the type of the dependency:

protocol DependencyDelegate {
  func doSomething(_ dependency: Dependency)
}

Ideally I'd be able to replace Dependency from the line above with the protocol I made the dependency conform to so that I can pass in the mock dependency during unit testing.

Here is the full example scenario where Dependency and DependencyDelegate are defined by a 3rd part framework:

extension Dependency: DependencyProtocol {}

class MyClass: DependencyDelegate {
  private let dependency: DependencyProtocol

  init(dependency: DependencyProtocol) {
    self.dependency = dependency
  }

  func doSomething(_ dependency: Dependency) {

  }
}

protocol DependencyDelegate {
  func doSomething(_ dependency: Dependency) // <---- How do I deal with this in unit tests?
}

class MockDependency: DependencyProtocol {
  ...
}

class MyClassTests: XCTestCase {
  func test() {
    let myClass = MyClass(dependency: MockDependency())
    myClass.doSomething(
  }
}

How can I unit test this delegate relationship between the dependency and my class without passing in an actual instance of Dependency into the delegate method of MyClass?



Solution 1:[1]

Pass in a subclass of Dependency where all methods are overridden.

(As you note, this is only for an API you can't change yourself.)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jon Reid