Search code examples
swiftunit-testinggenericsxctestxctestcase

Swift unit testing of function with generic parameter


I have a function defined as follows:

func parse<T: Mappable>(_ data: Data, _ completion: (Result<[T]>) -> Void) {
    completion(Result {
        do {
            let decodedData: Any = try decode(data)
            let checkedArray: [AnyObject] = try check(decodedData)
            let models: [T] = mapToModels(checkedArray)
            return models
        } catch {
            throw error
        }
    })
}

When I try to run the following unit test:

func testInvalidData() {
    let test = "test"
    let invalidData = test.data(using: .utf8)

    parse(invalidData, { result in
  //^Generic parameter 'T' could not be inferred
        switch result {
        case .success(let users):
            XCTFail()
        case .failure(let error):
            XCTAssertNotNil(error)
        }
    })
}

As commented above I get the error Generic parameter 'T' could not be inferred.

This function compiles, builds and works fine otherwise (when not unit testing).

Any idea how to test?


Solution

  • The error explains that the type of the result parameter in the completion handler could not be inferred. This means you must explicitly declare its type:

    func testInvalidData() {
        let test = "test"
        let invalidData = test.data(using: .utf8)
    
        parse(invalidData, { (result: Result<[DesiredTypeHere]>) in
        // ^Replace 'DesiredTypeHere' with expected type
            switch result {
            case .success(let users):
                XCTFail()
            case .failure(let error):
                XCTAssertNotNil(error)
            }
        })
    }