xcode 将捕获错误视为测试失败

标签 xcode swift unit-testing

我编写了以下函数:

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:.

来源:NSJSONSerialization


发生的事情是 message 不是可以用 json 表示的对象。我的猜测是 wspace 包含无法转换为 json 的类型。

关于xcode 将捕获错误视为测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34726792/

相关文章:

来自 xCode 6 的 iOS Master-Detail 应用程序模板不能在 iOS 7 上运行

objective-c - SMJobSubmit() 能否用于执行由 SMJobBless 安装的特权助手?

ios - 将 UI 图像更改为字符串数组

android - 不休眠测试 PendingIntent 发送

ios - iOS NSZombiesEnabled =是

swift - 我想要在 child 更改为 nil 时调用 FIRDataEventTypeChildChanged 而不是 ChildRemoved?

ios - 在 iOS 上原生渲染 UILabel/UITextfield 中的 LaTeX 代码

perl - 我怎样才能将不同种类的 Perl 测试分开,这样我就不必全部运行它们了?

c++ - 单元测试引用关键部分类

iOS 编程将 Storyboard 转换为 NIB