XCTAssertThrowsError Assertion Example

In this tutorial, you will learn how to use the XCTAssertThrowsError assertion in Xcode Unit Test.

The XCTAssertThrowsError asserts that an expression throws an error and it helps us write a unit test to verify that a method under the test will throw an error if we give it input parameters that cause an error.

If you are interested in video lessons on how to write Unit tests and UI tests to test your Swift mobile app, check out this page: Unit Testing Swift Mobile App

XCTAssertThrowsError Summary

func XCTAssertThrowsError<T>(_ expression: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line, _ errorHandler: (Error) -> Void = { _ in })

Parameters

  • expression – An expression that can throw an error,
  • message – An optional description of the failure,
  • file – The file in which failure occurred. Defaults to the file name of the test case in which this function was called,
  • line – The line number on which failure occurred. Defaults to the line number on which this function was called,
  • errorHandler – An optional handler for errors that are thrown by expression.

Let’s have a look at an example of how this assertion can be used.

XCTAssertThrowsError Example

Let’s assume we have a Model struct that needs to be validated.

struct SignupFormModel {
    let firstName: String
    let lastName: String
    let email: String
    let password: String
    let repeatPassword: String
}

To validate this model class I will create a very simple validator class with one method that can throw an Error.

class SignupFormValidator {
    let formModel: SignupFormModel
    init(formModel: SignupFormModel) {
        self.formModel = formModel
    }
}

extension SignupFormValidator {
    
    func isValidPassword() throws -> Bool {
        
        if formModel.password.contains("{") {
             throw AppErrors.PasswordContainsIlligalCharacter
        }
 
        return true
    }
}

The isValidPassword() method will throw an error if the provided password contains an illegal password character. The implementation of this password validation method is, of course, primitive and is written this way for the purpose of simplicity.

And here is an error itself.

enum AppError: Error {
    case PasswordContainsIlligalCharacter
}

Let’s write a unit test method.

func testSignupFormValidator_whenIlligalCharacterUsedInPassword_ShouldThrowError() {
     // Arrange
     let signupFormModel = SignupFormModel(firstName: "Sergey",
                               lastName: "Kargopolov",
                               email: "[email protected]",
                               password: "1234567{",
                               repeatPassword: "1234567")
     let sut = SignupFormValidator(formModel: signupFormModel)
 
     // Act and Assert
     XCTAssertThrowsError(try sut.isValidPassword(), "A PasswordContainsIlligalCharacter Error should have been thrown but no Error was thrown") { error in
         XCTAssertEqual(error as? AppError, AppError.PasswordContainsIlligalCharacter)
     }
 }

Here is how this code looks and works in my Xcode when I put all of it together and run.

XCTAssertThrowsError Example in Swift

I hope this tutorial was of some help to you.

Happy unit testing 🙋🏻‍♂️

Leave a Reply

Your email address will not be published. Required fields are marked *

Free Video Lessons

Enter your email and stay on top of things,

Subscribe!