how to write a unit test with swift testing, give me an example please.

Generated on 8/21/2024

1 search

To write a unit test using Swift Testing, you can follow these steps. Swift Testing is a new framework introduced by Apple, designed to be expressive and easy to use. Here's a simple example to get you started:

  1. Create a Test Target: First, ensure you have a test target in your Xcode project. You can add one by choosing File > New > Target and selecting Unit Testing Bundle.

  2. Import the Testing Module: In your test file, import the Swift Testing framework.

  3. Write a Test Function: Define a function and use the @Test attribute to mark it as a test. This attribute tells Xcode that the function is a test case.

  4. Use the expect Macro: Within your test function, use the expect macro to evaluate expressions and verify that your code behaves as expected.

Here's an example of a simple test:

import SwiftTesting

@Test
func testAddition() {
    let sum = 2 + 2
    expect(sum == 4, "Sum should be 4")
}

In this example, the testAddition function checks if the sum of 2 and 2 equals 4. The expect macro is used to assert that the condition is true.

For more detailed information and advanced features like parameterized tests, you can refer to the session Meet Swift Testing from WWDC 2024. This session covers the building blocks of Swift Testing and provides insights into writing expressive and efficient tests.