Mark Lilback
Mark Lilback

Reputation: 1164

xcode treating catching an error as a test failure

I've written the following function:

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)")
    }
}

Here is a unit test that should pass:

func testSendMessageFailure() {
    let dict = ["foo":wspace!, "bar":22]
    session!.sendMessage(dict)
    XCTAssertNil(wsSrc.lastStringWritten)
}

But the test fails with the message:

test failure: -[Rc2SessionTests testSendMessageFailure()] failed: failed: caught "NSInvalidArgumentException", "Invalid type in JSON write (Rc2.Rc2Workspace)"

That isn't a failure. It is what I expect! Does this mean it is impossible to write a unit test that calls a function that has an error handler that handles the error?

How can I tell XCTest/Xcode that a caught error/exception does not mean a test failed?

Upvotes: 0

Views: 766

Answers (1)

Craig Siemens
Craig Siemens

Reputation: 13276

do-catch statements are only for catching error thrown by the function. They do not catch exceptions. Exceptions are used to show that there is a programming error.

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

Source: NSJSONSerialization


What is happening is that message is not an object that can be represented in json. My guess would be that wspace contains a type that can not be converted to json.

Upvotes: 2

Related Questions