Skip to content

Generate generic mocks for protocols with associated types #336

@wvteijlingen-npo

Description

@wvteijlingen-npo

Given the following protocol:

protocol Foo<Output> {
    associatedtype Output
    func fetch() -> Output
}

The current generated mock uses Any for the associated type. This makes it awkward to use the mock, because we need to typecast it at the usage site since Any is usually not the concrete type we want. I know we can specify a concrete type using /// @mockable(typealias: Output = String), but that defeats the purpose of the associated type by limiting it to a single concrete type.

Current

class FooMock: Foo {
    init() { }

    typealias Output = Any


    private(set) var fetchCallCount = 0
    var fetchHandler: (() async throws -> Output)?
    func fetch() async throws -> Output {
        fetchCallCount += 1
        if let fetchHandler = fetchHandler {
            return try await fetchHandler()
        }
        fatalError("fetchHandler returns can't have a default value thus its handler must be set")
    }
}

Expected

Would it instead be possible to generate a mock like this?

class FooMock<T>: Foo {
    init() { }

    typealias Output = T

   // ... etc
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions