我正在尝试使用swift测试我的UICollectionViewDataSource
,但是在尝试使单元格出列时它会引发异常。例外似乎没有为重用标识符注册类。在我的故事板中,我注册了一个类和标识符,所以当我运行应用程序工作正常,但我试图孤立地测试
// 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")
}
}
答案 0 :(得分:2)
有趣的是,此测试引发异常的原因是因为我从未将collectionView
和dataSource
链接在一起。我认为这意味着UICollectionView
将不允许您在没有数据源的情况下注册单元格。固定代码如下:
func testDataSourceReturnsACell() {
let indexPath = NSIndexPath(forItem: 0, inSection: 0)
collectionView!.dataSource = dataSource // d'oh
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")
}