2015-12-17 25 views
1

我在Xcode中編寫腳本來運行一些UI測試,我想使用一些全局變量。
我第一次嘗試是聲明的變量在@interfacestrong類型,像這樣:爲什麼@interface中聲明的變量中的值不會在XCTest中的方法之間持續存在?

@interface Extended_Tests : XCTestCase 
@property (strong) NSMutableArray *list; 
@property (strong) NSString *name; 
@end 

,但沒有奏效。
我最終使用老式C方法來聲明方法外的變量。

我的問題是,爲什麼不工作?爲什麼變量中的值不會在所有方法中持續存在?

編輯: 我的方法:

- (void)testMultiUser1 { 
    [[[XCUIApplication alloc] init] launch]; 
    XCUIApplication *app = [[XCUIApplication alloc] init]; 
    [app.buttons[@"Sign-in button"] tap]; 
    sleep(5); 
    user1 = [app.staticTexts elementBoundByIndex:0].label; 
    [app.otherElements[@"LibraryView"] tap]; 
    sleep(5); 
    _list = [[NSMutableArray alloc] init]; 
    for(int i = 0; i < 3; i++){ 
     XCUIElementQuery *file1 = [[app.cells elementBoundByIndex:i] descendantsMatchingType:XCUIElementTypeStaticText]; 
     NSString *number = [file1 elementBoundByIndex:0].label; 
     [_list addObject:number]; 
    } 
    XCTAssert(_list); 
} 

我預計這將變量保存到陣列_list這樣我就可以在這樣的另一種方法使用它:

-(void)testMultiUser3{ 
    //Go into Library and make sure top 3 files are different from user1 
    XCUIApplication *app = [[XCUIApplication alloc] init]; 
    [app.otherElements[@"LibraryView"] tap]; 
    sleep(5); 

    NSMutableArray *user2files = [[NSMutableArray alloc] init]; 
    for(int i = 0; i < 3; i++){ 
     XCUIElementQuery *list1 = [[app.cells elementBoundByIndex:i] descendantsMatchingType:XCUIElementTypeStaticText]; 
     NSString *number = [list1 elementBoundByIndex:0].label; 
     [user2files addObject:number]; 
    } 
    XCTAssert(!([user2files[0] isEqualToString:_list[0]] && [user2files[1] isEqualToString:_list[1]] && [user2files[2] isEqualToString:_list[2]])); 
    } 
+1

您發佈的一小段代碼沒有聲明任何變量。它聲明瞭兩個屬性。也許你應該有更多相關的代碼顯示你真正做了,並解釋你有什麼確切的問題,更新你的問題。 – rmaddy

回答

3

你的問題是特定到XCTest。

每個運行的測試運行在測試用例類的新實例中。在你的情況下,爲每個測試實例化一個新的Extended_Tests對象。這就是爲什麼如果你在一次測試中設置了任何一個變量,你將不會在另一次測試中看到這些變化。

一般來說,如果測試不依賴其他測試的副作用,那麼最好是最好的,因爲您無法自行運行這些測試。如果您使用共享設置方法設置狀態並在兩種狀態下使用,最好。

如果你絕對必須的測試之間共享變量,那麼你可以使用類的靜態方法(那些具有的+而不是一個聲明 - )與靜態變量或像你一樣使用全局變量。

+0

Objective-C沒有類屬性。它有類方法。 – NobodyNada

+0

是的,真實的,但你可以使用任何一種方法在這裏模擬它們:http://stackoverflow.com/questions/695980/how-do-i-declare-class-level-properties-in-objective-c –

+0

也許用@NobodyNada在技術上是正確的,可以用你的答案來回答。然而更好的參考可能(http://stackoverflow.com/questions/15979973/setting-static-variables-in-objective-c/15980334#15980334)在Objective-C設置靜態變量],但隨後也許我米偏置;-) – CRD

相關問題