← Back to Blog

[Swift] Improve test feedback by passing file and line to XCTest assertion

2020-12-05·1 min read
SwiftiOSTestingNetworkingAI / ML

To get clear understanding why a test fails, provide two simple parameters on any of helper method created in XCTest and forward it to any XCTAssert calls. So that Xcode will highlight the right line of code that is responsible for test failures.

Image below is for test without file and line argument. The failure message is only XCTAssertNotNil failed which is not clear and can't really tell why it's fail.

To improve feedback, on Xcode 11 and below, use #file and #line as default parameters and Xcode will highlight the correct line with a better failure message like the image on very top of this article. Here is the example:

private func makeSUT(file: StaticString = #file, line: UInt = #line) -> HTTPClient {
  let sut = URLSessionHTTPClient()
  trackMemoryLeak(sut, file: file, line: line)
  return sut
}

On Xcode 12, #file is now called #filePath

private func makeSUT(file: StaticString = #filePath, line: UInt = #line) -> HTTPClient {}

for additional info, here is the resultErrorFor method looks like when I create test for network request.

private func resultErrorFor(data: Data?, response: URLResponse?, error: Error?, file: StaticString = #file, line: UInt = #line) -> Error? {
  let result = resultFor(data: data, response: response, error: error, file: file, line: line)
  switch result {
    case let .failure(error):
      return error
    default:
      XCTFail("Expected failure, got \(result) instead", file: file, line: line)
      return nil
  }
}