Registers a block of teardown code to be run after the current test method ends.
Call addTeardownBlock(_:) during a test method's execution to register a block of code to be called when the test method ends.
Registered teardown blocks are called before the tearDown() instance method for their associated test case is executed. Teardown blocks are run on the main thread, but can be registered from any thread. Each registered block is run once, in last-in, first-out order, executed serially.
Use teardown blocks to write test-specific teardown code alongside associated setup code. For example, if a test method needs to create a resource that must be deleted when the test completes, write the code to create the resource, followed immediately by code that registers a teardown block to delete the resource.
Listing 1 tests that a string can be written to a temporary file on disk and read back into a new string from the same file. The temporary file is deleted as part of the test's teardown process.
The sole test method in this test case, testReadAndWriteDataToTemporaryFile(), calls a convenience method named temporaryFileURL() to construct a URL to a temporary file location on disk. In addition to constructing the URL, the temporaryFileURL() method also registers a teardown block that deletes the temporary file during test teardown. You can call the temporaryFileURL() method multiple times from the same test method, or from multiple different test methods, and it will always clean up any temporary file at the returned URL when the test method completes. Registering a teardown block at the point that the URL is constructed keeps the setup and teardown code closely coupled, and removes the need to track file state in an instance variable on the test case subclass.