Search code examples
iosswiftunit-testinguikitcollectionview

Unit Testing UICollectionView.indexPath(for: UICollectionViewCell)


I am trying to unit test this bit of code in a ViewController

    func categoryTextEditedAt(_ cell: UICollectionViewCell, _ text: String) {
        guard let indexPath = self.collectionView.indexPath(for: cell), text != "" else {return}

        //Rest of the codes to be tested
    }

And in my Unit Test to test the above function is as follows:

    func testCategoryTextEditedAt() {
        sut.viewDidLoad()
        sut.collectionView.reloadData()
        let cell = sut.collectionView.dataSource?.collectionView(sut.collectionView, cellForItemAt: IndexPath(item: 0, section: 0))
        sut.categoryTextEditedAt(cell!, "testString")
    }

but I am keep getting 'nil' for the indexPath inside categoryTextEditedAt(:) function. As I debug, I found that inside testCategoryTextEditedAt() cell has a value but self.collectionView.indexPath(for:cell) keeps returning 'nil' for 'indexPath.'

How can I go about this process?


Solution

  • For those who are curious how to unit test collectionViewDelegateMethod:

        func categoryTextEditedAt(_ cell: UICollectionViewCell, _ text: String) {
            guard let indexPath = self.collectionView.indexPath(for: cell), text != "" else {return}
    
            //Rest of the codes to be tested
        }
    

    you can do something like

    func testCategoryTextEditedAt() {
        class MockCV: UICollectionView {
            override func indexPath(for cell: UICollectionViewCell) -> IndexPath? {
                let anyIndexPathWhichEverYoulike = IndexPath(item:0, section:0)
                return anyIndexPathWhichEverYoulike
            }
        }
        sut.collectionView = MockCV()
        let cell = sut.collectionView.dataSource?.collectionView(sut.collectionView, cellForItemAt: IndexPath(item: 0, section: 0))
        sut.categoryTextEditedAt(cell!, "testString")
    }