0

我正在测试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)
    }
}

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

XCTAssertThrowsError 失败:没有抛出错误。

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

4

1 回答 1

0

XCTAssertThrowsError由于@mag_zbc,它不会使函数抛出异常,它只是断言。

我将单元测试修改为:

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

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

它通过了测试。

于 2019-05-17T14:56:45.990 回答