0

I'm writing a unit-test to a class that uses PHAsset type. I mocked it as below:

class PHAssetMock: PHAsset {
    let date: Date
    let uuid: UUID

    init(dateStr: String) {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MM-dd-yyyy HH:mm"
        self.date = dateFormatter.date(from: dateStr)!
        self.uuid = UUID()
    }

    override var creationDate: Date? {
        return date
    }

    override var hash: Int {
        let hash = Int(self.date.timeIntervalSinceNow)
        return hash
    }


    static func ==(lhs: PHAsseMock, rhs: PHAsseMock) -> Bool {
        return lhs.date.timeIntervalSinceNow == rhs.date.timeIntervalSinceNow
    }

}

When a function that uses mocked objects tries to insert it in a dictionary I'm getting an exception:

func foo(assets: [PHAsset]) {
    var label: [T: String]()
    for asset in assets {
        label[asset] = "undefined" // Exception: "NSInternalInconsistencyException", "Must have a uuid if no _objectID"
    }
}

When debugging, the override hash var is being called.

Sanich
  • 1,739
  • 6
  • 25
  • 43

1 Answers1

2

I had the same issue with the PHAsset when unit testing Photos framework. Overriding isEqual function helped to get rid of the exception.

class Mock : PHAsset {

    let _localIdentifier: String   = UUID().uuidString
    let _hash: Int                 = UUID().hashValue

    override var localIdentifier: String {
        return _localIdentifier
    }

    override var hash: Int {
        return _hash
    }

    override func isEqual(_ object: Any?) -> Bool {
        guard let object = object as? Mock else {
            return false
        }
        return self.localIdentifier == object.localIdentifier
    }
}