【问题标题】:Running tests after an asynchronous setUp method is finished在异步 setUp 方法完成后运行测试
【发布时间】:2015-09-04 03:21:20
【问题描述】:

我有一个具有异步设置方法的 XCTTestClass。这将需要一些时间(必须解析文件,将它们插入 bd 等),我想确保我的测试仅在此设置完成后运行。

我该怎么做?

【问题讨论】:

    标签: objective-c cocoa tdd xctest


    【解决方案1】:

    在您的-setup 方法中,使用上述信号量或使用dispatch_group。 dispatch_group 是我的首选方法。

    @implementation XCTTestSubClass()
    {
        dispatch_group_t _dispatchGroup;
    }
    @end
    
    -(id)init
    {
        _dispatchGroup = dispatch_group_create();
        return [super init];
    }
    
    -(void)setup
    {
        dispatch_group_async(_dispatchGroup, dispatch_get_current_queue(), ^{
            //your setup code here.
        });
    }
    

    然后覆盖-invokeTest 并确保组块(设置)已完成运行。

    -(void)invokeTest
    {
        dispatch_group_notify(group, dispatch_get_current_queue(), ^{
            [super invokeTest];
        });
    }
    

    这保证了测试只会在-setup 完成后运行。

    【讨论】:

      【解决方案2】:

      您可以使用信号量等到从异步调用中返回结果。

      dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
      // Do your async call here
      // Once you get the response back signal:
      [self asyncCallWithCompletionBlock:^(id result) {
          dispatch_semaphore_signal(semaphore);
      }];
      dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-19
        • 1970-01-01
        • 1970-01-01
        • 2023-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多