Assertions

In all the tests of the previous example, we used only one assertion, but XCTest comes with several types of assertions. Let's have a look at the most important ones.

All the assertions are based on a fundamental one:

XCTAssert(expression: Bool)

This checks whether the expression is true, otherwise, it stops and makes the test fail. In theory, we could use only this one to cover all the possible types of tests, but the other assertions help the reader understand the semantics of the test and what the developer wanted to express. Hence, a good rule is to use the more specific assertion needed for the test we are currently writing.

Slightly more precise assertions are the Boolean assertions, which check whether a value is true or false:

XCTAssertTrue(expression: Bool)
XCTAssertFalse(expression: Bool)

XCTAssert is equivalent to XCTAssertTrue.

When we want to test whether two objects or scalars are equal, we must use the equality assertions:

XCTAssertEqual(expression: Equatable)
XCTAssertNotEqual(expression: Equatable)

For float or double, a series of assertions allows to pass an accuracy, otherwise, because of the rounding, we could have a false negative, as follows:

XCTAssertEqual(expression1: FloatingPoint, expression2: FloatingPoint, accuracy: FloatingPoint)
XCTAssertNotEqual(expression1: FloatingPoint, expression2: FloatingPoint, accuracy: FloatingPoint)

We can also assert whether a value is greater than another:

XCTAssertGreaterThan(expression1: Comparable, expression2: Comparable)
XCTAssertLessThan(expression1: Comparable, expression2: Comparable)

To check whether a value is nil, we use the following:

XCTAssertNil(expression: Any?)
XCTAssertNotNil(expression: Any?)

The Swift way of handling errors is to throw exceptions, so we must have a way to check whether an expression throws an exception:

XCTAssertThrowsError(expression: T)
XCTAssertNoThrow(expression: T)

Finally, sometimes we have to fail the test without checking anything, as a body of a guard for example. In this case, we can use the following:

XCTFail(message: String)

As a final note, all the previous assertions also have a format where you can pass a message to the Assert function, a message that will be shown by Xcode if the assertion fails, like in the following example: