我编写了以下函数:
func sendMessage(message:Dictionary<String,AnyObject>) {
do {
let json = try NSJSONSerialization.dataWithJSONObject(message, options: [])
let jsonStr = NSString(data: json, encoding: NSUTF8StringEncoding)
self.wsSource.writeString(jsonStr as! String)
} catch let err as NSError {
Rc2LogError ("error sending json message on websocket:\(err)")
}
}
这是一个应该通过的单元测试:
func testSendMessageFailure() {
let dict = ["foo":wspace!, "bar":22]
session!.sendMessage(dict)
XCTAssertNil(wsSrc.lastStringWritten)
}
但测试失败并显示消息:
test failure: -[Rc2SessionTests testSendMessageFailure()] failed: failed: caught "NSInvalidArgumentException", "Invalid type in JSON write (Rc2.Rc2Workspace)"
那不是失败。这是我所期望的!这是否意味着不可能编写调用具有处理错误的错误处理程序的函数的单元测试?
我如何告诉 XCTest/Xcode 捕获的错误/异常并不意味着测试失败?
最佳答案
do-catch
语句仅用于捕获函数抛出的错误。他们不捕获异常。异常用于表明存在编程错误。
If obj will not produce valid JSON, an exception is thrown. This exception is thrown prior to parsing and represents a programming error, not an internal error. You should check whether the input will produce valid JSON before calling this method by using
isValidJSONObject:
.
发生的事情是 message
不是可以用 json 表示的对象。我的猜测是 wspace
包含无法转换为 json 的类型。
关于xcode 将捕获错误视为测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34726792/