11

我一直在寻找一种方法来使用 SenTestingKit 在我的客户端代码和我们的服务器之间进行一些集成测试。我没有运气。似乎一旦代码在方法中运行,对象就会被销毁。这意味着任何异步响应都不会调用选择器。

问题:

  1. 有没有办法让对象保持实例化,直到我认为合适的时候销毁它 - 即。测试完成后?
  2. 如果不是,我怎么能创建一个阻塞(即同步动作)直到测试完成的类?

仅供参考,我正在运行一个我知道预期结果的测试服务器。

我已经做了一些谷歌搜索,但还没有看到关于这一点的任何证据。我相信其他人也会感兴趣。

4

5 回答 5

30

您可以使用信号量等待异步方法完成。

- (void)testBlockMethod {
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

    // Your block method eg. AFNetworking
    NSURL *url = [NSURL URLWithString:@"http://httpbin.org/ip"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        NSLog(@"IP Address: %@", [JSON valueForKeyPath:@"origin"]);
        STAssertNotNil(JSON, @"JSON not loaded");
        // Signal that block has completed
        dispatch_semaphore_signal(semaphore);
    } failure:nil];
    [operation start];

    // Run loop
    while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW))
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
                                 beforeDate:[NSDate dateWithTimeIntervalSinceNow:10]];
    dispatch_release(semaphore);

}

http://samwize.com/2012/10/03/sentestingkit-does-not-support-wait-for-blocks/

于 2012-10-03T14:21:25.013 回答
9

两种选择:

  • 切换到GHUnit,它实际上包含对等待异步事件的支持
  • 缩小测试的设计范围,以便您可以按原样测试事物。例如,测试您的控制器代码是否导致选择器被分离并运行,并(单独)测试该选择器是否完成了它应该做的事情。如果这两件事都有效,那么您可以确信您的控制器分离了正确的工作。
于 2011-05-31T16:18:39.473 回答
5

Kiwi 支持异步测试Kiwi是适用于 iOS 的行为驱动开发 (BDD)库,它扩展了 SentTestingKit (OCUnit),因此易于设置和使用。

另外,请查看:

于 2011-05-31T16:21:45.930 回答
3

这个项目https://github.com/hfossli/AGAsyncTestHelper有一个非常方便的宏

WAIT_WHILE(<expression_to_evaluate>, <max_duration>);

哪个能让你像这样编写测试

- (void)testDoSomething {

    __block BOOL somethingIsDone = NO;

    [MyObject doSomethingAsyncThenRunCompletionBlockOnMainQueue:^{
        somethingIsDone = YES;
    }];

    WAIT_WHILE(!somethingIsDone, 1.0); 
    NSLog(@"This won't be reached until async job is done");
}
于 2013-07-26T09:57:42.383 回答
0

查看 SenTestingKitAsync 项目 - https://github.com/nxtbgthng/SenTestingKitAsync。相关博客在这里 - http://www.objc.io/issue-2/async-testing.html

于 2013-08-19T09:01:42.513 回答