Your First Test with @Test

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Defining and Validating Behavior

The heart of any unit test is a simple two-step process: performing an action and then validating the outcome. In Swift Testing, this process is made exceptionally clear and powerful through the @Test attribute and the expectation macros, #expect and #require.

Your First Test with @Test

In the world of XCTest, a function was identified as a test if its name began with the prefix “test”. Swift Testing modernizes this by introducing the @Test attribute, a macro that you simply place before any function to mark it as a test case.  

Making Assertions with #expect

Once you have performed an action in your test, you need to check the result. This is done using an “expectation.” The primary tool for this in Swift Testing is the #expect macro.  

Enforcing Preconditions with #require

Sometimes, a test has certain preconditions that must be met for the rest of the test to be meaningful. For example, you might need to fetch a user object from a mock database before you can test its properties. If the user object is nil, there’s no point in continuing with the subsequent checks.

See forum comments
Download course materials from Github
Previous: Swift Testing Next: Grouping Tests with @Suite