gpt4 book ai didi

objective-c - 为什么 GHUnit 中的异步测试中的错误断言会导致应用程序崩溃,而不仅仅是测试失败?

转载 作者:太空狗 更新时间:2023-10-30 03:24:00 25 4
gpt4 key购买 nike

这个问题的浏览量很少,还没有答案。如果您有关于如何更改此问题以吸引更多眼球的建议,我很乐意听取他们的意见。干杯!

我正在使用 GHAsyncTestCase测试我的自定义 NSOperation。我将测试用例设置为操作对象的委托(delegate),并在完成后在主线程上调用 didFinishAsyncOperation

当断言失败时,它会抛出一个异常,测试用例应该捕获该异常以将测试呈现为“失败”。但是,我的应用程序并没有出现这种预期的行为,而是在断言失败后立即被 Xcode 中止。

*** Terminating app due to uncaught exception 'GHTestFailureException', reason: ''NO' should be TRUE. This should trigger a failed test, but crashes my app instead.'

我显然做错了什么。谁能告诉我?

@interface TestServiceAPI : GHAsyncTestCase
@end

@implementation TestServiceAPI

- (BOOL)shouldRunOnMainThread
{
return YES;
}

- (void)testAsyncOperation
{
[self prepare];

MyOperation *op = [[[MyOperation alloc] init] autorelease];

op.delegate = self; // delegate method is called on the main thread.

[self.operationQueue addOperation:op];

[self waitForStatus:kGHUnitWaitStatusSuccess timeout:1.0];
}

- (void)didFinishAsyncOperation
{
GHAssertTrue(NO, @"This should trigger a failed test, but crashes my app instead.");

[self notify:kGHUnitWaitStatusSuccess forSelector:@selector(testAsyncOperation)];
}

@end

最佳答案

当我终于休息时,我已经挖掘了一个星期来找到解决这个问题的方法。对赏金问题几乎没有任何看法,也没有人愿意尝试回答,这有点奇怪。我在想这个问题可能很愚蠢,但没有人投反对票,也没有人愿意纠正它。 StackOverflow 已经饱和了吗?

一个解决方案。

诀窍是不要断言回调方法中的任何内容,而是将断言放回原始测试中。 wait方法其实是在阻塞线程,之前没有想到。如果您的异步回调接收到任何值,只需将它们存储在 ivar 或属性中,然后在您的原始测试方法中基于它们进行断言。

这会处理不会导致任何崩溃的断言。

- (void)testAsyncOperation
{
[self prepare];

MyOperation *op = [[[MyOperation alloc] init] autorelease];

op.delegate = self; // delegate method is called on the main thread.

[self.operationQueue addOperation:op];

// The `waitfForStatus:timeout` method will block this thread.
[self waitForStatus:kGHUnitWaitStatusSuccess timeout:1.0];

// And after the callback finishes, it continues here.
GHAssertTrue(NO, @"This triggers a failed test without anything crashing.");
}

- (void)didFinishAsyncOperation
{
[self notify:kGHUnitWaitStatusSuccess forSelector:@selector(testAsyncOperation)];
}

关于objective-c - 为什么 GHUnit 中的异步测试中的错误断言会导致应用程序崩溃,而不仅仅是测试失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7613761/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com