使用通知的设计的单元测试

发布于 2024-11-11 17:25:54 字数 2067 浏览 2 评论 0原文

我在测试一些使用通知的逻辑时遇到困难。我读过强制执行特定的NSNotifications已发送,但这并不能真正解决我所看到的问题。

[SomeObject PerformAsyncOperation] 创建一个 NSURLRequest 并将其自身设置为响应委托。根据响应的内容,SomeObject 将成功或失败的 NSNotification 发布到默认的 NSNotificationCenter

我的测试的问题是,调用 PerformAsyncOperation 后,测试不会等待发送响应。相反,它继续断言 - 该断言失败,因为请求/响应没有时间发送/接收/解析。

代码如下:

-(void)testMethod {
    SomeObject *x = [[SomeObject alloc] init];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                        selector:@selector(success:)
                                            name:SomeObjectSuccess
                                          object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                        selector:@selector(failure:)
                                            name:SomeObjectFailure
                                          object:nil];

    operationCompleted = false; // declared in .h

    [x PerformAsyncOperation:@"parameter"];

    STAssertTrue(operationCompleted , @"Operation has completed.");

    [[NSNotificationCenter defaultCenter] removeObserver:self name:SomeObjectSuccess object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SomeObjectFailure object:nil];

    [x release];
}

-(void) failure:(NSNotification *) notification {
   operationCompleted = true;
   NSLog(@"Received failure message.");
}

-(void) success:(NSNotification *) notification {
   operationCompleted = true;
   NSLog(@"Received success message.");
}

我尝试在调用 PerformAsyncOperation 以及空的 while (!operationCompleted) 循环后休眠线程。两者都不起作用 - 睡眠线程仍然无法断言,并且 while 循环永远不会退出。我还尝试将断言移至 success:failure: 中,但由于 OCUnit 期望每个方法都是测试方法,因此它只是立即执行所有三个方法并退出(无需等待 NSURLRequest 的响应,这就是练习的重点!)。

任何想法或见解将不胜感激。谢谢!

I'm having difficulty testing some logic that uses notifications. I've read about enforcing that particular NSNotifications are sent, but that doesn't really address the problem I'm seeing.

[SomeObject PerformAsyncOperation] creates an NSURLRequest and sets itself as the response delegate. Depending on the content of the response, SomeObject posts a success or failure NSNotification to the default NSNotificationCenter.

The problem with my test is that after PerformAsyncOperation is called, the test doesn't wait for the response to be sent. Instead, it continues on with the assert - which fails, because the request/response hasn't had time to be sent/received/parsed.

Here is the code:

-(void)testMethod {
    SomeObject *x = [[SomeObject alloc] init];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                        selector:@selector(success:)
                                            name:SomeObjectSuccess
                                          object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                        selector:@selector(failure:)
                                            name:SomeObjectFailure
                                          object:nil];

    operationCompleted = false; // declared in .h

    [x PerformAsyncOperation:@"parameter"];

    STAssertTrue(operationCompleted , @"Operation has completed.");

    [[NSNotificationCenter defaultCenter] removeObserver:self name:SomeObjectSuccess object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SomeObjectFailure object:nil];

    [x release];
}

-(void) failure:(NSNotification *) notification {
   operationCompleted = true;
   NSLog(@"Received failure message.");
}

-(void) success:(NSNotification *) notification {
   operationCompleted = true;
   NSLog(@"Received success message.");
}

I've tried sleeping the thread after the call to PerformAsyncOperation, as well as an empty while (!operationCompleted) loop. Neither works - sleeping the thread still fails the assert, and the while loop never exits. I've also tried moving the asserts into success: and failure:, but because OCUnit expects each method to be a test method, it just executes all three methods immediately and quits (without waiting for the NSURLRequest's response, which is the whole point of the exercise!).

Any ideas or insight would be greatly appreciated. Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

隐诗 2024-11-18 17:25:54

您面临的问题不是通知,而是同步的。相反,您正在触发异步操作。为了使其成为可重复的测试,您需要重新同步。

NSTimeInterval timeout = 2.0;   // Number of seconds before giving up
NSTimeInterval idle = 0.01;     // Number of seconds to pause within loop
BOOL timedOut = NO;

NSDate *timeoutDate = [[NSDate alloc] initWithTimeIntervalSinceNow:timeout];
while (!timedOut && !operationCompleted)
{
    NSDate *tick = [[NSDate alloc] initWithTimeIntervalSinceNow:idle];
    [[NSRunLoop currentRunLoop] runUntilDate:tick];
    timedOut = ([tick compare:timeoutDate] == NSOrderedDescending);
    [tick release];
}
[timeoutDate release];

除此之外,您知道操作已完成,或者测试已超时。

The problem you face is not notifications, which are synchronous. Rather, it is that you are firing off an asynchronous operation. To make this a repeatable test, you need to resynchronize things.

NSTimeInterval timeout = 2.0;   // Number of seconds before giving up
NSTimeInterval idle = 0.01;     // Number of seconds to pause within loop
BOOL timedOut = NO;

NSDate *timeoutDate = [[NSDate alloc] initWithTimeIntervalSinceNow:timeout];
while (!timedOut && !operationCompleted)
{
    NSDate *tick = [[NSDate alloc] initWithTimeIntervalSinceNow:idle];
    [[NSRunLoop currentRunLoop] runUntilDate:tick];
    timedOut = ([tick compare:timeoutDate] == NSOrderedDescending);
    [tick release];
}
[timeoutDate release];

Beyond this point, you know that either the operation completed, or the test timed out.

吖咩 2024-11-18 17:25:54

为简单起见,如果可能,请使用同步网络请求。

- (void)testExample
{
    [self measureBlock:^{

        NSURLRequest *request = [[NSURLRequest alloc] initWith...];

        NSHTTPURLResponse *response = nil;
        NSData *data = [NSURLConnection sendSynchronousRequest:request
                                         returningResponse:&response
                                                     error:nil];

        XCTAssertEqual(response.statusCode,200);

        // process the data from response ... call the delegate methods or whatever

        NSObject *object = [NSJSONSerialization JSONObjectWithData:data
                                                       options:NSJSONReadingMutableContainers
                                                         error:nil];
        XCTAssertTrue([object isKindOfClass:[NSArray class]]);
    }];
}

For simplicity reasons, and if possible, use the synchronous network requests.

- (void)testExample
{
    [self measureBlock:^{

        NSURLRequest *request = [[NSURLRequest alloc] initWith...];

        NSHTTPURLResponse *response = nil;
        NSData *data = [NSURLConnection sendSynchronousRequest:request
                                         returningResponse:&response
                                                     error:nil];

        XCTAssertEqual(response.statusCode,200);

        // process the data from response ... call the delegate methods or whatever

        NSObject *object = [NSJSONSerialization JSONObjectWithData:data
                                                       options:NSJSONReadingMutableContainers
                                                         error:nil];
        XCTAssertTrue([object isKindOfClass:[NSArray class]]);
    }];
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文