【发布时间】:2019-05-17 14:35:46
【问题描述】:
我正在测试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 失败:没有抛出错误。
我不确定为什么会这样。有什么建议吗?
【问题讨论】:
-
测试失败,因为
createSpeechRecognization应该抛出,但它没有。SFSpeechRecognizer(locale:)是一个可失败的初始化程序,但是对于参数Locale.current它返回了一个有效实例,因此createSpeechRecognization没有抛出。一切都按预期工作。 -
XCTAssertThrowsError 是否使 createSpeechRecognization 抛出异常?我想让它为零,这样我就可以测试错误处理了。
-
不,它断言它是否抛出 - 而对于
Locale.current它没有。 -
啊,谢谢你的澄清
-
使用函数
SFSpeechRecognizer.supportedLocales(),然后尝试使用它不支持的语言环境初始化SFSpeechRecognizer
标签: swift unit-testing error-handling xctest sfspeechrecognizer