I use the SocketRocket library to control the connection to Websocket. It connects fine, but I'm trying to run some unit tests, which should wait for the WS connection first. Since the only way to find out that WS is connected through its delegation method, I am having problems with the synchronous process. I want my unit testing method to setupsimply create a WS connection, and then tearDownclose it.
I applied two types of connection methods for my Websocket class. The first two are pretty simple, and I checked that they work as expected. Last - my attempt to block it primarily for testing purposes. I could not get it to work, and it just ends, waiting forever, so I think that the conceptual misunderstanding is on my part.
I guess my big question is: how can I stop execution in a test case to wait for a delegate to answer a call? The problem that arises in test cases is that I cannot just do all my tests in the completion block - the testing method sees this as success and terminates the program.
- (void)connect
{
DLog(@"Websocket is connecting now");
[_socket open];
}
- (void)connectWithCompletion:(WebsocketConnection)completion
{
DLog(@"Connecting now...");
[_onConnectBlocksToRun addObject:^{
completion(self.isConnected, self.socket);
}];
[_socket open];
}
- (bool)connectBlocking
{
sem = dispatch_semaphore_create(0);
[_socket open];
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
return _isConnected;
}
#pragma mark - Socket rocket delegate
- (void)webSocketDidOpen:(SRWebSocket *)webSocket
{
DLog(@"Websocket has opened");
_isConnected = YES;
_socket = webSocket;
for (void(^block)() in _onConnectBlocksToRun) {
block();
}
[_onConnectBlocksToRun removeAllObjects];
if (sem) {
dispatch_semaphore_signal(sem);
dispatch_release(sem);
}
}
source
share