0

我正在尝试向这个SimpleHTTPServer 示例添加一个 GHUnit 测试用例。该示例包括一个对我来说很好的 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 确实会收到通知。

4

1 回答 1

0
if (error == nil)

那应该是:

if (data != nil)

error这是传入的指向 NSError* 的指针 - 只有当调用者传递 nil 而不是对 NSError* 对象的引用时,它才会为 nil,这不是您的-testPortReuse方法所做的。

取消引用它也是不正确的(如if (*error == nil)),因为错误参数不能保证在出错时设置为 nil。返回值表示错误情况,错误参数中返回的值只有在出现错误时才有意义或可靠。始终检查返回值以确定是否发生错误,然后仅在确实出错时检查错误参数以获取详细信息。

换句话说,正如上面所写,您的-requestToURL:error:方法无法处理成功。很像查理辛。:-)

于 2011-03-31T20:52:30.150 回答