Thursday, 30 July 2020

Xcode UI tests: saveScreenshot(...) extension function

Taking a screenshot as part of an Xcode UI test and adding the screenshot to the test's output is a five-step shuffle as follows:

let screenshot = XCUIApplication().screenshot()
let attachment = XCTAttachment(screenshot: screenshot)
attachment.lifetime = .keepAlways
attachment.name = "SomeName"
add(attachment)

Wouldn't it be great if this could be reduced to a single line call as follows:

XCUIApplication().saveScreenshot(to: self, named: "SomeName")

To make this possible, all you need to do is add the following extension function to your UI testing bundle:

extension XCUIScreenshotProviding {
    
    func saveScreenshot(to activity: XCTActivity, named name: String) {
        let attachment = XCTAttachment(screenshot: screenshot())
        attachment.lifetime = .keepAlways
        attachment.name = name
        activity.add(attachment)
    }
}
You can find this extension function and others like it in the XCTestExtensions repo.

No comments: