xcodexctestxcode-ui-testingui-testingxctestcase

Get result of each test case executed in Xcode UI tests


I need the test status after each test case is executed in my test suite in Xcode. I know an observer can help in achieving it. But how do I use it in my tests?


Solution

  • You are on the right track and can achieve what you're wanting to do via the XCTestObservation protocol (https://developer.apple.com/documentation/xctest/xctestobservation). You can add an observer to your test case class and I'd recommend doing this in the setUp() method since it gets executed before each test method.

    override func setUp() {
        super.setUp()
    
        continueAfterFailure = false
    
        XCUIApplication().launch()
    
        XCTestObservationCenter.shared.addTestObserver(UITestObserver())
    }
    

    To do this you should implement a class that conforms to the XCTestObservation protocol and then provide your own implementation to the methods of interest to perform whatever actions you need/want. In your case you're probably going to want to provide an implementation for this method...

    optional public func testCase(_ testCase: XCTestCase, didFailWithDescription description: String, inFile filePath: String?, atLine lineNumber: Int)
    

    Here's a quick example of what this test observer class might look like...

    import XCTest
    
    public class UITestObserver: NSObject, XCTestObservation {
        public func testCase(_ testCase: XCTestCase,
                               didFailWithDescription description: String,
                               inFile filePath: String?,
                               atLine lineNumber: Int) {
            print("failure description: \(description)")
            print("failed test case: \(testCase)")
            if let filePath = filePath {
                print("failure at file path: \(filePath)")
            }
            print("failure at line: \(lineNumber)")
        }
    }
    

    This function I provided an example of above gets called whenever one of your test cases fails, so you don't need to "do" anything from within your test case class or methods.

    Hope this helps!