2
我試圖用swift測試UICollectionViewDataSource
,但在嘗試出隊時發生異常。異常看起來好像它沒有註冊重用標識符的類。在我的故事板我註冊類和標識,所以當我運行應用程序工作正常,但我想在隔離UICollectionView在快速單元測試中出隊引發異常
// CollectionViewDataSource.swift
import UIKit
class CollectionViewDataSource : NSObject, UICollectionViewDataSource {
private var items = [MediaItem]()
init(items: [MediaItem]) {
self.items = items
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.items.count
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as MediaItemCell
// .. cell property setting
return cell
}
}
測試文件來測試
// CollectionViewDataSourceTests.swift
import UIKit
import XCTest
class CollectionViewDataSourceTests: XCTestCase {
var dataSource: CollectionViewDataSource!
var collectionView: UICollectionView?
override func setUp() {
super.setUp()
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
let size = CGRect(x: 0, y: 0, width: 100, height: 100)
collectionView = UICollectionView(frame: size, collectionViewLayout: layout)
let movieA = Movie(title: "Title", year: 1980, slug: "", banner: "")
let movieB = Movie(title: "", year: 1980, slug: "", banner: "")
let items = [movieA, movieB]
dataSource = CollectionViewDataSource(items: items)
}
// This crashes when attempting to dequeue a cell. It's as if the collection
// view never registers the class properly
func testDataSourceReturnsACell() {
let indexPath = NSIndexPath(forItem: 0, inSection: 0)
// Register the cell
collectionView!.registerClass(MediaItemCell.self, forCellWithReuseIdentifier: "Cell")
let cell = dataSource.collectionView(collectionView!, cellForItemAtIndexPath: indexPath) as MediaItemCell
XCTAssert(cell.textLabel.text == "The Shawshank Redemption", "Data source should set cell text")
}
}