gpt4 book ai didi

xcode - 使用通知的设计的单元测试

转载 作者:行者123 更新时间:2023-12-04 13:24:40 25 4
gpt4 key购买 nike

我在测试一些使用通知的逻辑时遇到了困难。我读过 enforcing that particular NSNotifications are sent ,但这并不能真正解决我看到的问题。
[SomeObject PerformAsyncOperation]创建一个 NSURLRequest并将自己设置为响应委托(delegate)。根据响应的内容,SomeObject发布成功或失败NSNotification为默认 NSNotificationCenter .

我的测试的问题是在 PerformAsyncOperation 之后被调用时,测试不会等待发送响应。相反,它继续断言 - 失败,因为请求/响应没有时间发送/接收/解析。

这是代码:

-(void)testMethod {
SomeObject *x = [[SomeObject alloc] init];

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(success:)
name:SomeObjectSuccess
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(failure:)
name:SomeObjectFailure
object:nil];

operationCompleted = false; // declared in .h

[x PerformAsyncOperation:@"parameter"];

STAssertTrue(operationCompleted , @"Operation has completed.");

[[NSNotificationCenter defaultCenter] removeObserver:self name:SomeObjectSuccess object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:SomeObjectFailure object:nil];

[x release];
}

-(void) failure:(NSNotification *) notification {
operationCompleted = true;
NSLog(@"Received failure message.");
}

-(void) success:(NSNotification *) notification {
operationCompleted = true;
NSLog(@"Received success message.");
}

我尝试在调用 PerformAsyncOperation 后让线程休眠,以及一个空的 while (!operationCompleted)环形。两者都不起作用 - 休眠线程仍然使断言失败,并且 while 循环永远不会退出。我还尝试将断言移入 success:failure: ,但是因为 OCUnit 期望每个方法都是测试方法,所以它只是立即执行所有三个方法并退出(无需等待 NSURLRequest 的响应,这就是练习的重点!)。

任何想法或见解将不胜感激。谢谢!

最佳答案

您面临的问题不是通知,而是同步的。相反,您正在触发异步操作。要使这是一个可重复的测试,您需要重新同步事物。

NSTimeInterval timeout = 2.0;   // Number of seconds before giving up
NSTimeInterval idle = 0.01; // Number of seconds to pause within loop
BOOL timedOut = NO;

NSDate *timeoutDate = [[NSDate alloc] initWithTimeIntervalSinceNow:timeout];
while (!timedOut && !operationCompleted)
{
NSDate *tick = [[NSDate alloc] initWithTimeIntervalSinceNow:idle];
[[NSRunLoop currentRunLoop] runUntilDate:tick];
timedOut = ([tick compare:timeoutDate] == NSOrderedDescending);
[tick release];
}
[timeoutDate release];

超过这一点,您就知道操作已完成,或者测试已超时。

关于xcode - 使用通知的设计的单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6205491/

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