Use attachments to store a test’s output data for later analysis.
Tests often produce output such as files, images, screenshots, and data during their execution. You can store this test output for later analysis by wrapping it in an
XCTAttachment instance and adding it to the current test or activity. You can then view these attachments within Xcode’s test results browser alongside the test or activity that created them.
XCTAttachment provides several convenience initializers to create attachments for common data types such as images, screenshots, files, folders, strings, and custom objects that conform to
NSSecure or can be encoded to a property list. Alternatively, you can attach custom test output by creating an attachment from raw data in memory.
You associate an attachment with a test by calling the
add method on an instance of a type that conforms to the
XCTest automatically conforms to
XCTActivity, so you can add an attachment to the current test by calling
add from within any test method.
Alternatively, you can create and run a custom activity by calling the
run class method from anywhere in your testing code. This method runs a user-provided block of test code, passing an
XCTActivity instance to the block. Call
add on this
XCTActivity instance to add an attachment to the activity instead of the overall test.
Every attachment you create has a
uniform property containing a Uniform Type Identifier (UTI) that identifies the type of content stored in the attachment. Many of
XCTAttachment's convenience initializers determine an appropriate UTI to use from their provided content. Alternatively, you can provide a manual UTI value to represent a custom data format used in your app.
Based on the results of the download, the code above produces one of three outcomes:
If the data task returns an error, the test fails and the error’s description is logged as part of the failure.
If the data task succeeds but has an HTTP response status code of anything other than
200 OK, the response's header fields are added to the test as an XML property list attachment before the test fails, to assist with debugging the problem.
If the data task succeeds and retrieves some data, the retrieved data is added to the test as an attachment with a UTI of
"public, enabling Xcode to provide an appropriate Quick Look for the data within the Xcode test results browser. The attachment's lifetime property is set to
XCTAttachmentto store the HTML data even though the test succeeds.
Lifetime Keep Always
By default, a test’s attachments are discarded when the test passes successfully, to save on storage space. To persist an attachment even when its test passes, set the attachment’s
lifetime property to
XCTAttachment rather than the default value of
XCTAttachment. Alternatively, change the default lifetime for an entire test scheme by unchecking the “Attachments: Delete when each test succeeds” option in the “Options” tab of the scheme’s “Test” scheme action.