0

このSimpleHTTPServer exampleに 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) Web ブラウザを介して送信することも試みました。デリゲート メソッド-processURL-stopProcessingが呼び出されることはありません。問題は[fileHandle acceptConnectionInBackgroundAndNotify]、SimpleHTTPServer で NSFileHandleConnectionAcceptedNotifications-initWithTCPPort:delegate:が NSNotificationCenter に到達しないように思われるため、実行ループに関連する問題が疑われます。

問題は NSNotificationCenter ではなく NSFileHandle にあるよう[nc postNotificationName:NSFileHandleConnectionAcceptedNotification object:nil]ですinitWithTCPPort:delegate:

4

1 に答える 1

0
if (error == nil)

それは次のようになります。

if (data != nil)

errorこれは NSError* への渡されたポインターです。呼び出し元が NSError* オブジェクトへの参照の代わりに nil を渡した場合にのみ nil になりますが、これは-testPortReuseメソッドが行うことではありません。

if (*error == nil)エラー時にエラー引数が nil に設定されることが保証されていないため、( のように) 逆参照することも正しくありません。戻り値はエラー状態を示し、error 引数で返される値は、エラーが発生した場合にのみ意味があり、信頼できます。常に戻り値をチェックしてエラーが発生したかどうかを判断し、実際に問題が発生した場合にのみ、エラー パラメータの詳細を確認してください

つまり、上に書かれているように、あなたの-requestToURL:error:メソッドは成功を処理することができません。チャーリー・シーンにそっくり。:-)

于 2011-03-31T20:52:30.150 に答える