How to write unit tests

Asked on 06/16/2025

1 search

To write unit tests in Swift, you can follow these steps, as discussed in the WWDC sessions:

  1. Add a Test Target: Start by adding a test bundle target to your project in Xcode. You can do this by choosing "File" > "New" > "Target" and then selecting "Unit Testing Bundle" from the test section. Swift testing is the default choice in Xcode 16.

  2. Write a Test Function: Create a function and add the @test attribute to it. This attribute indicates that the function is a test, and Xcode will recognize it as such, providing a run button alongside it. Test functions can be global functions or methods in a type and can be marked async or throws.

  3. Use Expectations: Use the expect macro to evaluate the result of Swift expressions. This makes it easy to write complex checks and validate that your code behaves as expected.

  4. Parameterized Testing: You can write parameterized tests by adding parameters to your test functions. This allows you to test multiple inputs with a single test function, improving test coverage and reducing code duplication.

  5. Organize Tests: Use tags and test suites to organize your tests. Tags help you associate tests with common characteristics, while suites impose structure on test functions at the source level.

  6. Code Coverage: Enable code coverage in Xcode to determine how much of your code is executed when running your tests. This helps you identify gaps in your testing.

For more detailed guidance, you can refer to the sessions Meet Swift Testing and Go further with Swift Testing from WWDC 2024.