2013-11-20 101 views
0

即時通訊新單元測試和OCMock,所以這可能是一個明顯的答案,只是沒有找到答案谷歌。 我想測試模型對象的方法。 該方法具有下面的代碼:嘲笑一類 - iOS

//takes a filepath and a pk, sets the filepath to the 
BoxAppDelegate *delegate = [[UIApplication sharedApplication] delegate]; 
NSNumber *ifExistIndexInJson = [BoxJsonDataHelper pkExistInCurrentJson:[[[self.downloadQueue objectAtIndex:0] objectForKey:@"pk"] integerValue]]; 
if (ifExistIndexInJson) 
{ 
    [[[self.downloadQueue objectAtIndex:0] objectForKey:@"fields"] setObject:path forKey:@"content"]; 
    NSError *error = nil; 
    [[NSFileManager defaultManager] removeItemAtPath:[[[delegate.currentJsonData objectAtIndex:[ifExistIndexInJson integerValue]] objectForKey:@"fields"] objectForKey:@"content"] error:&error]; 
    [delegate.currentJsonData removeObjectAtIndex:[ifExistIndexInJson integerValue]]; 
    [delegate.currentJsonData addObject:[self.downloadQueue objectAtIndex:0]]; 
    [self.downloadQueue removeObjectAtIndex:0]; 
    if ([self.downloadQueue count] > 0) 
    { 
    [BoxServerRequestsObject downloadFileForPK:[[[self.downloadQueue objectAtIndex:0] objectForKey:@"pk"] integerValue]sender:self]; 
    } 
    else 
    { 
     //end the progress or whatever 
    } 
} 
else 
{ 
    [[[self.downloadQueue objectAtIndex:0] objectForKey:@"fields"] setObject:path forKey:@"content"]; 
    [delegate.currentJsonData addObject:[self.downloadQueue objectAtIndex:0]]; 
    [self.downloadQueue removeObjectAtIndex:0]; 
    if ([self.downloadQueue count] > 0) 
    { 
    [BoxServerRequestsObject downloadFileForPK:[[[self.downloadQueue objectAtIndex:0] objectForKey:@"pk"] integerValue]sender:self]; 
    } 
    else 
    { 
     //end the progress or whatever 
    } 

} 

我需要幾件事情幫助:

  1. 當我打電話[BoxJsonDataHelper pkExistInCurrentJson:...]。 BoxJsonDataHelper實際上是自我的,只是它是一個類方法而不是一個實例,所以我通過名稱來調用它,我怎樣才能僞造返回值的結果,使得它們不依賴?

  2. 如何在要刪除的程序的路徑中僞造文件?比如何檢查它被刪除?

  3. 如何模擬BoxServerRequestObject使該方法調用模擬對象而不是真實的對象?比我如何檢查它是否已被稱爲(也是一類方法)

我在單元測試的知識是有限的,我剛開始用OCMock,看了一些例子,所以我將不勝感激充分的答案: )

回答

0
  1. 您可以像實例方法一樣模擬類方法。他們一直嘲笑,直到模擬被釋放。

    id boxJsonDataHelperMock = [OCMockObject mockForClass:BoxJsonDataHelper.class]; [[[boxJsonDataHelperMock存根] andReturn:@(1)] pkExistInCurrentJson:OCMOCK_ANY]

  2. 你只是在這一點上測試是否NSFileManager作品?有了數據對象,我更願意寫實際的文字。爲什麼不只是聲稱文件在刪除後不存在?如果你想嘲笑,你應該嘲笑的NSFileManager「defaultManager」,並返回預期removeItemAtPath:error:

  3. 將模仿對象在下載隊列索引0

+0

我NIT-模仿對象但他們保持嘲笑,直到你致電-stopMocking或模擬被解除分配。如果您模擬了框架類的方法,例如NSURLConnection,那麼在完成測試後立即調用stopMocking就非常重要。 – ImHuntingWabbits