iosswiftswift-testing

Swift Testing Library and Checking for Thrown Exception


I am using Swift Testing Library and trying to see that the code throws the BankAccountError.invalidAmount exception. But I don't know how to check for the type in the test.

enum BankAccountError: Error {
    case invalidAmount(Double)
}

 @Test func depositNegativeAmountThrowsError() {
        
        let bankAccount = BankAccount(accountNumber: "1234", balance: 500)
        
        #expect("Invalid amount.", performing: {
            try bankAccount.deposit(amount: -100, depositType: .check)
        }, throws: { error in
            
            // how to make sure that error is of type BankAccountError.invalidAmount 
           
        })
    }

Here is my code and I am trying to figure out how can I pass the test by comparing the types.


Solution

  • You could unwrap the error to your type and use an if case... to get and check the value

    #expect("Invalid amount.", performing: {
            try bankAccount.deposit(amount: -100, depositType: .check)
    }, throws: { error in
        if case .invalidAmount(let amount) = error as? BankAccountError {
            return amount == -100
        }           
        return false
    })
    

    If you don't need to check the actual amount you can simplify the if case to

    if case .invalidAmount(let amount) = error as? BankAccountError {
        return true
    }