2011-03-31 16 views
0

我想一个GHUnit测试用例添加到这个SimpleHTTPServer example。这个例子包括一个适合我的Cocoa应用程序。但是我不能在测试用例中复制行为。HTTP服务器在Cocoa应用程序中工作,但不是测试用例 - 运行循环问题?

下面是测试类:通过网络浏览器

#import <GHUnit/GHUnit.h> 
#import "SimpleHTTPServer.h" 


@interface ServerTest : GHTestCase 
{ 
    SimpleHTTPServer *server; 
} 
@end 


@implementation ServerTest 

-(void)setUpClass 
{ 
    [[NSRunLoop currentRunLoop] run]; 
} 

- (NSString*)requestToURL:(NSString*)urlString error:(NSError**)error 
{ 
    NSURL *url = [NSURL URLWithString:urlString]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:1]; 
    NSURLResponse *response = nil; 
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:error]; 
    NSString *page = nil; 
    if (error == nil) 
    { 
     NSStringEncoding responseEncoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((CFStringRef)[response textEncodingName])); 
     page = [[NSString alloc] initWithData:data encoding:responseEncoding]; 
     [page autorelease]; 
    } 
    return page; 
} 

- (void)testPortReuse 
{ 
    unsigned int port = 50001; 
    NSError *error = nil; 
    NSString *path, *url; 

    server = [[SimpleHTTPServer alloc] initWithTCPPort:port delegate:self]; 
    sleep(10); 
    path = @"/x/y/z"; 
    url = [NSString stringWithFormat:@"http://localhost:%u%@", port, path]; 
    [self requestToURL:url error:&error]; 
    GHAssertNil(error, @"%@ : %@", url, error); 
    [server release]; 
} 

- (void)processURL:(NSURL *)path connection:(SimpleHTTPConnection *)connection 
{ 
    NSLog(@"processURL"); 
} 

- (void)stopProcessing 
{ 
    NSLog(@"stopProcessing"); 
} 

@end 

我试图通过发送请求的NSURLRequest,也(在sleep期间)。从不会调用代理方法-processURL-stopProcessing。这个问题似乎是在[fileHandle acceptConnectionInBackgroundAndNotify] SimpleHTTPServer -initWithTCPPort:delegate:不会导致任何NSFileHandleConnectionAcceptedNotifications达到NSNotificationCenter - 所以我怀疑涉及运行循环的一个问题。

这个问题似乎与NSFileHandle,而不是NSNotificationCenter,因为当[nc postNotificationName:NSFileHandleConnectionAcceptedNotification object:nil]被添加到initWithTCPPort:delegate:的末尾时,NSNotificationCenter确实得到通知。

回答

0
if (error == nil) 

这应该是:

if (data != nil) 

error这里是传入的指针指向一个NSError * - 它只会是零,如果调用者传递零,而不是引用的NSError *对象,这不是你的-testPortReuse方法所做的。

这也将是不正确取消对它的引用(如在if (*error == nil)),因为错误的论点并不能保证在错误被设置为零。返回值指示错误状态,并在错误参数返回的值是唯一有意义的或可靠的,如果有错误。经常检查返回值,以确定是否发生错误,然后检查细节错误参数只如果事情事实上已经出问题。

换句话说,因为它上面写的,你-requestToURL:error:方法不能处理成功。很像Charlie Sheen。 :-)

+0

谢谢。我在我的代码中解决了这个问题,但是这对我所问的问题没有帮助。现在数据总是零,错误“请求超时”。 – jlstrecker 2011-04-01 03:11:39

+0

您是否尝试过使用更长的timeoutInterval? – 2011-04-01 10:47:18

+0

是的,最多10秒。 – jlstrecker 2011-04-01 15:19:11

相关问题