The expect
macro in the new Swift Testing framework is used to assert that a condition is true. It is similar to the XCTAssertTrue
function in XCTest. In this article, let us take a look how we can use the expect
macro in Swift testing.
To begin with, create a new test function in your test suite. Then, use the #expect
macro to assert that a condition is true. If the condition is false, the test will fail.
import Testing
struct MyTest {
@Test func myFirstTest() {
let result = "one"
let expected = "one"
#expect(result == expected)
}
}
If you take a look at the documentation, you would see that the expect
macro has the following signature:
@freestanding(expression) macro expect( _ condition: Bool, _ comment: @autoclosure () -> Comment? = nil, sourceLocation: SourceLocation = #_sourceLocation )
This tell us the following:
The macro always takes a boolean value as the first argument.
This means that any expression that evaluates to a boolean value can be passed to the
expect
macro.The following are some examples of expressions that can be passed to the
expect
macro:#expect(event.start < event.end) #expect(collection.contains(element)) #expect(collection.isEmpty)
The second argument is an optional comment.
This is useful when you want to provide additional information about the assertion.
#expect(result == expected, "The result should be equal to the expected value")
Here is how it shows up if the test fails.
Refer to Comment | Apple Developer Documentation for more information.
The macro captures the source location of the assertion.
This will be used to display the file and line number where the assertion failed.
Refer to SourceLocation | Apple Developer Documentation for more information.
That’s it! This is how you can use the expect
macro in Swift testing.
This is a significant improvement over the XCTAssert
functions in XCTest. There is no need to remember the function names for the type of assertion you want to make. The expect
macro is more readable and concise. It also provides better error messages when the test fails.