2017-02-04 32 views
1

我有一个应用程序,其中包含一个cocoapod,其中包含应用程序后面的引擎。在这个cocoapod中,我有一个基本类的共享实例。`同步'在XCTest中不工作

+ (Restaurant *)current { 
    @synchronized(self) { 
     if (current == nil) { 
      current = [[Restaurant alloc] initWithId:0]; 
     } 
    } 
    return current; 
} 

现在,我跑在其他一些代码的一些单元测试我的应用程序。这看起来是这样的:

- (void)testPOSTCodeGeneration { 
    [[Restaurant current] setMainTable:4]; 

    NSLog(@"Main table in test: %d", [[Restaurant current] mainTable]); 

    Generator *generator = [[Generator alloc] init]; 

    XCTAssertEqualObjects([[Restaurant current] mainTable], generator.table); 
} 

而在Generator.m,我沿着这个线的东西:

- (void)init { 
    ... 
    self.table = [[Restaurant current] mainTable]; 
    ... 
} 

奇怪的是,这个测试失败。除非设置了不同的数字,否则mainTable的默认值为0。所以即使我将它设置为4(并且Main table in test:记录了4),它将返回0.是否@synchronized与Xcode unittests不兼容?还是有人知道这里还有什么?

回答

0

苹果推荐使用dispatch_once,而不是同步的,因此你可以试试这个代码:

+ (Restaurant *)current { 
    static Restaurant *current=nil: 
    static dispatch_once_t onceToken = 0; 
    dispatch_once(&onceToken, ^{ 
     current = [[Restaurant alloc] initWithId:0]; 
    } 
    return current; 
} 

链接到苹果的文档:https://developer.apple.com/reference/dispatch/1447169-dispatch_once

0

mainTable不是一个对象,所以不要拨打XCTAssertEqualObjects。请使用XCTAssertEquals