Search code examples
iosswiftxcodexctest

Swift - Display assertion failures inline in Xcode like XCTest failures?


I'd like to write some custom test assertion types and have them be displayed in Xcode, similarly to how the XCTAssert() failures are displayed:

Is there a way for me to hook into Xcode and make this happen?

I want my own assertion function to show its error inline the same way here:

enter image description here

The best resource I've found so far is Apple's XCTest source code, but I haven't been able to understand if that even includes the logic that is responsible for displaying the error UI.


Solution

  • The easiest way is to call XCTFail() from your custom assertion, but pass along the file name and line number of the call site. For example:

    func verify(myThing: MyThing, file: StaticString = #filePath, line: UInt = #line) {
       // Do your verification. Then when you want to fail the test,
       XCTFail("Some message about \(myThing)", file: file, line: line)
    }
    

    At the call site, you'd let the default arguments provide file and line. So it would just look like:

    verify(myThing: thing)
    

    In Swift, XCTest assertions are global functions. This means your helper can also be a global function, and shared across test suites without having to subclass XCTestCase.