我想用GameKit框架构建一个单元测试。 实际上我已经实现了一个创建两个线程的单元测试。 一个用于服务器,一个用于客户端。
这里是服务器线程主要方法的代码:
@implementation ServerThread - (void)main { session = [[SessionManager alloc] initWithSessionId:@"TEST" displayName:@"Server" sessionMode:GKSessionModeServer]; session.delegate = self; running = YES; while (running) { NSLog(@"Server running"); [NSThread sleepForTimeInterval:1.0]; } [session release]; session = nil; }
相同的代码适用于客户端,但是sessionMode = GKSessionModeClient。
不幸的是,客户端永远不会连接到服务器! 日志:
2011-03-21 19:48:04.630 otest[41695:2f03] Server ready, peerId=352270827 2011-03-21 19:48:04.631 otest[41695:2f03] Server running 2011-03-21 19:48:04.651 otest[41695:2e07] Client ready, peerId=1781598997 2011-03-21 19:48:04.652 otest[41695:2e07] Client running 2011-03-21 19:48:05.633 otest[41695:2f03] Server running 2011-03-21 19:48:05.653 otest[41695:2e07] Client running 2011-03-21 19:48:06.633 otest[41695:2f03] Server running 2011-03-21 19:48:06.654 otest[41695:2e07] Client running 2011-03-21 19:48:07.634 otest[41695:2f03] Server running 2011-03-21 19:48:07.655 otest[41695:2e07] Client running 2011-03-21 19:48:08.635 otest[41695:2f03] Server running 2011-03-21 19:48:08.656 otest[41695:2e07] Client running
这里,单元测试方法:
- (void)test { serverThread = [[ServerThread alloc] init]; clientThread = [[ClientThread alloc] init]; [serverThread start]; [clientThread start]; // The main thread must wait the end while ([serverThread isExecuting] || [clientThread isExecuting]) { [NSThread sleepForTimeInterval:1.0]; } [clientThread release]; clientThread = nil; [serverThread release]; serverThread = nil; }
这里是SessionManager初始化程序:
- (id)initWithSessionId:(NSString *)aSessionId displayName:(NSString *)aDisplayName sessionMode:(GKSessionMode)aSessionMode { if ((self = [super init])) { peers = [[NSMutableArray alloc] init]; // Peers need to have the same sessionID set on their GKSession to see each other. sessionId = [aSessionId retain]; displayName = [aDisplayName retain]; sessionMode = aSessionMode; gkSession = [[GKSession alloc] initWithSessionID:sessionId displayName:displayName sessionMode:sessionMode]; gkSession.delegate = self; [gkSession setDataReceiveHandler:self withContext:nil]; gkSession.available = YES; switch (sessionMode) { case GKSessionModeServer: NSLog(@"Server ready, peerId=%@", gkSession.peerID); break; case GKSessionModeClient: NSLog(@"Client ready, peerId=%@", gkSession.peerID); break; case GKSessionModePeer: NSLog(@"Peer ready, peerId=%@", gkSession.peerID); break; } } return self; }
GKSession的委托'didChangeState'方法永远不会在服务器上和客户端上调用。