【发布时间】:2014-07-21 05:48:25
【问题描述】:
我一直在尝试测试我创建的一些使用NSNetServer 类等执行网络操作的类。我在确保调用委托方法时遇到了一些问题。
我尝试了很多方法,包括:
使用[NSThread sleepForTimeInterval:5.0f]; 和[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:5.0f]]; 在其他操作发生时简单地暂停。 NSRunLoop 方法在第一次调用时有效(如下面的示例代码所示),但在第二次调用时崩溃。我明白这也不是“正确”的做事方式,但我不知道“正确”的方式是什么。
使用NSCondition 和NSConditionLock 类,这似乎只是锁定了代码并且从不调用回调。
在回调方法中更改的变量上使用while循环,同上。
为简单起见,下面是带有几个额外 cmets 和一些测试的代码:
- (void)testCheckCredentials
{
[self.server start];
// Create a client
self.nsb = [[NSNetServiceBrowser alloc] init];
// Set the delegate to self
self.nsb.delegate = self;
// Search for the server
[self.nsb searchForServicesOfType:self.protocol inDomain:@""];
// Wait for the service to be found and resolved
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:self.timeout]];
XCTAssertTrue(self.serviceWasFound, @"Service was not found");
// Open the connection to the server
XCTAssertTrue([self.serverConnection open], @"Connection to server failed to open");
// Wait for the client to connect
/* This is where it crashes */
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:self.timeout]];
XCTAssertTrue(self.clientDidConnect, @"Client did not connect");
/* Further, more class-specific tests */
}
- (void)netServiceBrowser:(NSNetServiceBrowser *)aNetServiceBrowser didFindService:(NSNetService *)service moreComing:(BOOL)moreComing
{
NSLog(@"Found a service: %@ (%@)", service.name, service.domain);
if ([self.serverName isEqualToString:service.name]) {
self.serviceWasFound = YES;
}
}
- (void)clientDidConnect:(RCFClientConnection *)client
{
XCTAssertNotNil(client, @"Connected client is nil");
self.clientConnection = client;
self.clientDidConnect = YES;
}
我还尝试在 NSCondition 对象上执行 lock:
[self.nsb searchForServicesOfType:self.protocol inDomain:@""];
// Wait for the service to be found and resolved
[self.lock lockWhenCondition:1];
XCTAssertTrue(self.serviceWasFound, @"Service was not found");
和
self.serviceWasFound = YES;
[self.lock unlockWithCondition:1]
使用 lock 方法时,永远不会调用 netServiceBrowser:didFindService:moreComing: 方法,我使用时也是这样:
while (!self.serviceWasFound) {};
我仍在学习 Objective-C,但我完全陷入了这个问题。
【问题讨论】:
标签: ios objective-c macos xctest