Use XCTUnwrap to Clean Up Your Unit Tests

XCTUnwrap.png

Writing good tests is hard enough as it is, and optionals just complicate things further. To maintain sanity and make sure you (and the rest of your team) understand what exactly is being tested keeping your unit test code clean is a must.

Look at the follow view model object:

struct ViewModel {
    enum TitleDisplayMode {
        case short
        case long
        case none
    }

    var titleDisplayMode: TitleDisplayMode

    var title: String? {
        switch titleDisplayMode {
        case .short:
            return "Hello"
        case .long:
            return "Hello World"
        case .none:
            return nil
        }
    }
}

You’ll likely want to write some tests to make sure title is giving you back the correct String based on the titleDisplayMode. To test the short option, for example, you could write a test that looks like this:

func testShortTitle() {
    let viewModel = ViewModel(titleDisplayMode: .short)
    if let title = viewModel.title {
        XCTAssertEqual(title, "Hello")
    } else {
        XCTFail("Expected the title to be Hello")
    }
}

Now while that test totally works, it has this messy if/let/else going on there just to check if the title was set correctly. If you had to test a bunch of different cases you can easily see how your testing code could get out of hand. With XCTUnwrap that same test can be rewritten to look like this:

func testShortTitle() throws {
    let viewModel = ViewModel(titleDisplayMode: .short)
    let title = try XCTUnwrap(viewModel.title)
    XCTAssertEqual(title, "Hello")
}

So much cleaner and easier to see exactly what is going on. One little thing to note is that XCTUnwrap will throw any errors if the optional is empty, so you need to mark your test as throws to support it.

That’s it! Now go clean up those tests that you’ve totally been writing for every new feature and bug you work on.

Previous
Previous

Setting SwiftUI Modifiers With the Attributes Inspector

Next
Next

Fonts in SwiftUI