0

I'm testing the error handling for SFSpeechRecognizer. I'm not able to get the function to throw an error using XCTAssertThrowsError().

Creating SFSpeechRecognizer will return an object or nil if there is no locale.

public convenience init?() // Returns speech recognizer with user's current locale, or nil if is not supported

public init?(locale: Locale) // returns nil if the locale is not supported

func createSpeechRecognization(locale : Locale) throws -> SFSpeechRecognizer {
    guard let speechRecognizer = SFSpeechRecognizer(locale: locale) else {
        throw SpeechToTextError.speechRecognizerIsNil
    }
    return speechRecognizer
}

Here is the unit test function where I attempt to throw:

func testCreateSpeechToTextAudioSessionNotNotAvailable() {
    XCTAssertThrowsError(try sut.createSpeechRecognization(locale: Locale.current)) {error in
        XCTAssertEqual(error as? SpeechToTextError, SpeechToTextError.speechRecognizerIsNil)
    }
}

The unit test failed due to the error:

XCTAssertThrowsError failed: did not throw an error.

I'm not sure why it is happening. Any suggestions?

ZGski
  • 2,398
  • 1
  • 21
  • 34
Meep
  • 501
  • 6
  • 24
  • 2
    Test failed because `createSpeechRecognization` was supposed to throw, but it didn't. `SFSpeechRecognizer(locale:)` is a failable initializer, but for the parameter `Locale.current` it returned a valid instance, thus `createSpeechRecognization` didn't throw. Everything works as expected. – mag_zbc May 17 '19 at 14:46
  • does XCTAssertThrowsError makes createSpeechRecognization throw the exception? I want to get it to be nil so I can test the error handling. – Meep May 17 '19 at 14:48
  • No, it asserts whether it throws - and for `Locale.current` it didn't. – mag_zbc May 17 '19 at 14:49
  • ah, thanks for clarification – Meep May 17 '19 at 14:51
  • Use a function `SFSpeechRecognizer.supportedLocales()` and then try to initialize `SFSpeechRecognizer` with a locale it doesn't support – mag_zbc May 17 '19 at 14:51
  • If there are SFSpeechRecognizer.unsupportedLocales(), then I'll gladly try it. I'll see if I can set the Locale with some string to get SFSpeechRecognizer to be nil. – Meep May 17 '19 at 14:53

1 Answers1

0

XCTAssertThrowsError doesn't make the function throw the exception, it just asserts, thanks to @mag_zbc.

I modified the unit test to:

func testCreateSpeechToTextAudioSessionNotNotAvailable() {
    var locale : Locale = Locale(identifier: "pwned")

    XCTAssertThrowsError(try sut.createSpeechRecognization(locale: locale)) {error in
        XCTAssertEqual(error as? SpeechToTextError, SpeechToTextError.speechRecognizerIsNil)
    }
}

And it passed the test.

ZGski
  • 2,398
  • 1
  • 21
  • 34
Meep
  • 501
  • 6
  • 24