为什么当我测试某个方法引发异常而该方法引发异常时,测试是否停止? [英] Why, when I am testing that a method throws an exception and the method throw an exception, does the test stop?
问题描述
我有一个单元测试,用于测试在条件
存在且<$ c时,方法
是否引发异常$ c>方法确实按预期引发异常。
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");
}
以下是例外来源:
- (void)methodWithCondition:(someType)condition {
if (condition) {
[NSException raise: @"condition is true!" format: @"condition is true!"];
}
}
为什么测试在行中停止,例外是抛出?测试没有继续,它在那行停止,当我期望它继续并从 XCTAssertThrows()$ c $返回
1
时c>,使测试成功。相反,测试通过Xcode停止,使我进入抛出的行,并带有绿色的线程1:断点1.1,并且调试器出现在控制台中。
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.
推荐答案
为什么在执行被抛出时测试会停止?
因为您有一个断点,它会停止执行。
"Why does the test stop when the execution is thrown?"
Because you have a breakpoint, which stops execution.
因为您有未处理的异常。未处理的异常会导致您的程序崩溃。
Because you have an unhandled exception. Unhandled exceptions cause your program to crash.
这个问题的简单答案是不抛出异常。在其他编程语言(如Java)中,这是完全标准的。但是在Objective-C中,我们实际上并没有例外。在Objective-C中,应保存TRULY异常行为的异常。
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.
话虽如此,强烈建议您找到另一种方式来处理您所要解决的问题重新尝试处理,这是您在Objective-C中处理异常的方式:
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
}
这篇关于为什么当我测试某个方法引发异常而该方法引发异常时,测试是否停止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!