gpt4 book ai didi

swift - UICollectionView dequeue 在快速单元测试中引发异常

转载 作者:可可西里 更新时间:2023-11-01 01:41:15 25 4
gpt4 key购买 nike

我正在尝试使用 swift 测试我的 UICollectionViewDataSource,但它在尝试使单元格出队时引发异常。异常似乎没有为重用标识符注册类。在我的 Storyboard 中,我注册了一个类和标识符,所以当我运行该应用程序时工作正常,但我正在尝试单独测试

//  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")

}

}

最佳答案

有趣的是,这个测试引发异常的原因是因为我从未将 collectionViewdataSource 链接在一起。我认为这意味着 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")
}

关于swift - UICollectionView dequeue 在快速单元测试中引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29471171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com