Search code examples
xcodexctestxcuitest

Capturing screenshot within a function located in a separate file from your XCTestCase


I'm currently writing an automated iOS test using XCUITest. I have the main .swift file where the test actually is called from, and then I have a separate .swift file that has a few functions that I made that extend the XCUIElement class.

Is there a way to attach a screenshot in these extension functions that can be included in the test results? I can't seem to figure it out. Thank you!


Solution

  • Here is a post I made explaining how to take screenshots and attach them to activities within your test. The attachment and activity APIs can be used anywhere within your tests, not just within your test class.

    To take a screenshot of just the current element in your XCUIElement extension, you can just call screenshot() instead of element.screenshot() as you would need to elsewhere. To take a screenshot of the whole screen, initialise a new XCUIApplication and call screenshot() on that.

    extension XCUIElement {
         func tapTwice() {
            takeScreenshot()
            tap()
            tap()
        }
        func takeScreenshot() {
            XCTContext.runActivity(named: "Take screenshot") { activity in
                let screenshot = XCTAttachment(screenshot: screenshot())
                screenshot.lifetime = .keepAlways
                activity.add(screenshot)
            }
        }
    }