我正在测试SFSpeechRecognizer的错误处理。我无法使用XCTAssertThrowsError()获得函数引发错误。

如果没有语言环境,创建SFSpeechRecognizer将返回一个对象或nil

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
}

这是我尝试抛出的单元测试函数:
func testCreateSpeechToTextAudioSessionNotNotAvailable() {
    XCTAssertThrowsError(try sut.createSpeechRecognization(locale: Locale.current)) {error in
        XCTAssertEqual(error as? SpeechToTextError, SpeechToTextError.speechRecognizerIsNil)
    }
}

单元测试由于以下错误而失败:



我不确定为什么会这样。有什么建议?

最佳答案

由于@mag_zbc,XCTAssertThrowsError不会断言该函数,它只是断言。

我将单元测试修改为:

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

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

它通过了测试。

关于swift - Swift 4-XCTAssertThrowsError失败: did not throw an error,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56188618/

10-10 15:55