2013-07-25 39 views
4

如果我從故事板中的標識符出列單元格,如何以單元測試方式調用cellForRowAtIndexPath而不是單元格爲nil?單元測試cellForRowAtIndexPath使用storyBoards時

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    MyCustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCustomCell]; 

    cell.guestNameText.text = self.details.guestName; 

    return cell; 
} 

不工作,把一個破發點以上dequeReusableCell被稱爲細胞是零之後:

ETA:更新的工作代碼,以通過測試:

- (void)setUp { 

    [super setUp]; 
    _detailVC_SUT = [[UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil] 
    instantiateViewControllerWithIdentifier:kDetailsVC]; 
    _myService = [OCMockObject niceMockForClass:[MyService class]]; 
    _detailVC_SUT.service = _myService; 
} 


- (void)test_queryForDetailsSucceeded_should_set_cell_text_fields { 

    [_detailVC_SUT view]; // <--- Need to load the view for this to work 
    Details *details = [DetailsBuilder buildStubDetails]; 
    [_detailVC_SUT queryForDetailsSucceededWithDetails:details]; 

    [self getFirstCellForGuestName]; 
} 

- (void)getFirstCellForGuestName { 

    MyCustomTableViewCell *guestNameCell = (MyCustomTableViewCell*)[_detailVC_SUT tableView:_detailVC_SUT.detailsTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; 

    expect(guestNameCell.guestNameText.text).to.equal(@"Mark"); 
} 
+0

在你的測試中,視圖是否真的被加載? – Wain

+0

是的,只是添加了[_detailVC_SUT視圖];但對於guestCell仍然顯示爲零。更新完整代碼 –

+0

現在調用視圖加載視圖後,現在工作,錯過了,但現在它的作品,感謝您的建議Wain! –

回答

6

這裏是如何我測試表視圖和他們的單元格。這裏的關鍵是在視圖控制器上調用beginAppearanceTransition以從故事板加載它。

class MyTests: XCTestCase { 
    var viewController: UIViewController! 

    override func setUp() { 
    super.setUp() 

    let storyboard = UIStoryboard(name: "MyStoryboard", bundle: nil) 
    viewController = storyboard.instantiateViewControllerWithIdentifier("myViewControllerId") 
    viewController.beginAppearanceTransition(true, animated: false) 
    } 

    override func tearDown() { 
    super.tearDown() 

    viewController.endAppearanceTransition() 
    } 


    func testShowItemsFromNetwork() { 
    // 
    // Load the table view here ... 
    // 

    let tableView = viewController.tableView 

    // Check the number of table rows 

    XCTAssertEqual(3, tableView.dataSource?.tableView(tableView, numberOfRowsInSection: 0)) 

    // Check label text of the cell in the first row 

    let indexPath = NSIndexPath(forRow: 0, inSection: 0) 
    let cell = tableView.dataSource?.tableView(tableView, cellForRowAtIndexPath: indexPath) 
    XCTAssertEqual("Test cell title", cell!.textLabel!.text) 
    } 
}