Why, when I am testing that a method throws an exception and the method throw an exception, does the test stop?

扶醉桌前 提交于 2019-12-20 04:24:39

问题


I have a unit test that tests if method throws an exception when condition is present, and method does throws exception as expected.

- (void)testMethodThrowsWhenConditionIsPresent {
    XCTAssertThrows([Foo methodWithCondition: condition], @"Condition is true, method should throw exception");
}

Here is the exception source:

- (void)methodWithCondition:(someType)condition {
    if (condition) {
        [NSException raise: @"condition is true!" format: @"condition is true!"];
    }
}

Why does the test stop at the line the exception is thrown? The test does not go on, it stops at that line, when I expect it to continue and return 1 from XCTAssertThrows(), making the test succeed. The test instead stops with Xcode bringing me to the line it was thrown, with a green `Thread 1: breakpoint 1.1' and the debugger appearing in the console.


回答1:


"Why does the test stop when the execution is thrown?"

Because you have a breakpoint, which stops execution.


"Why, after removing the breakpoint, does my application crash when the exception is thrown?"

Because you have an unhandled exception. Unhandled exceptions cause your program to crash.


"How can I handle an exception so it won't crash my program?"

The easy answer to this question is to simply NOT throw an exception. In other programming languages, like Java, this is perfectly standard. But in Objective-C, we don't really do exceptions. In Objective-C, exceptions should be saved for TRULY exceptional behavior.

With that said, and a strong suggestion for you to find another way to handle whatever it is you're trying to handle, this is how you handle an exception in Objective-C:

@try {
    // code that could throw an exception
}

@catch (NSException *e) {
    // handle the exception...
}

@finally {
    // post try-catch code, executed every time
}


来源:https://stackoverflow.com/questions/22384572/why-when-i-am-testing-that-a-method-throws-an-exception-and-the-method-throw-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!