Testing optionals can require boilerplate code to unwrap it. It can also affect the readability of the test.
Let’s look on the following example:
1 2 3 4 5 6 7 8 |
struct Person { let name: String let address: Address? } struct Address { let postCode: String } |
If we want to test the address we have to unwrap it first.
1 2 3 4 5 6 7 8 9 10 |
func test_address() { let address = Address(postCode: "42131") let person = Person(name: "Fragi", address: address) if let address = person.address { XCTAssertEqual(address.postCode, "42131") } else { XCTFail("Failed to unwrap address") } } |
We can improve the readability of the test by using XCTUnwrap, as follows:
1 2 3 4 5 6 7 8 |
func test_address_with_xctunwrap() throws { let address = Address(postCode: "42131") let person = Person(name: "Fragi", address: address) let unWrappedAddress = try XCTUnwrap(person.address) XCTAssertEqual(unWrappedAddress.postCode, "42131") } |