【问题标题】:Different behaviour of asynchronous code in test target and deployment target测试目标和部署目标中异步代码的不同行为
【发布时间】:2013-09-21 20:30:33
【问题描述】:

在尝试将 TDD 应用于异步代码时,我发现在部署目标中运行的相同代码在测试目标中不起作用。 我使用 CLLocationManager 发现的这个问题的一个例子:

- (void)testReceivingLocation
{
    locationManager = [[CLLocationManager alloc] init];
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    locationManager.delegate = self;
    locationManager.pausesLocationUpdatesAutomatically = NO;
    if ([CLLocationManager locationServicesEnabled])
    {
        [locationManager startUpdatingLocation];
    }
    startLocation = nil;

    NSDate *until = [NSDate dateWithTimeIntervalSinceNow:10];
    while ([until timeIntervalSinceNow] > 0)
    {
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
                                 beforeDate:until];
    }
    XCTAssert(alreadyReceivedLocation, @"Location wasn't received.");
}

-(void)locationManager:(CLLocationManager *)manager
   didUpdateToLocation:(CLLocation *)newLocation
          fromLocation:(CLLocation *)oldLocation
{
    alreadyReceivedLocation = true;
    // Never actually get there.
}

可能是什么问题?

【问题讨论】:

    标签: objective-c xcode ocunit


    【解决方案1】:

    您应该详细说明 [SomeClass performActionWithAsyncResponse] 的工作原理。

    假设在主队列的一个块中调用completionWithResult,这将不起作用,因为线程在测试方法完成后结束。在生产环境中情况并非如此,因为应用程序一直在运行。

    通常我使用这样的代码来等待异步调用,这些调用会在测试中回调主队列。

    NSDate *until = [NSDate dateWithTimeIntervalSinceNow:30];
    while ([loopUntil timeIntervalSinceNow] > 0) 
    {
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
                                 beforeDate:until];
    }
    

    您还可以通过一个条件来停止 while 循环,该条件指示异步工作是否已完成,例如使用测试的属性。

    有关异步测试模式的更多信息,请参阅这篇文章: Pattern for unit testing async queue that calls main queue on completion

    【讨论】:

    • 感谢指点!我用我使用的特定方法更新了问题,并尝试使用您的代码而不是 sleep()。不幸的是,什么都没有改变……
    • 啊,CLLoactionManager 我敢打赌模拟器中根本没有任何位置更新。您可以尝试在具有 GPS 定位的设备上运行测试吗? CLLocationManager 在模拟器中的行为有点不同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-29
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 2016-07-31
    • 1970-01-01
    相关资源
    最近更新 更多