-1

How would you create a test function to compare the contents of two objects of the same class?

Background: I have a function which extracts data from a CSV file and uses that data to create an object. I want to know if this function is generating the correct output.

infinite369
  • 65
  • 1
  • 11

2 Answers2

3

Look at Equatable protocol. E.g.

extension MyClass: Equatable
{
  static func ==(lhs: MyClass, rhs: MyClass) -> Bool
  {
    return (lhs.property1 == rhs.property1) && (lhs.allData == rhs.allData)
  }
}
Chris Shaw
  • 1,610
  • 2
  • 10
  • 14
  • Oh, I see. So I would need to create a logical check to compare each member variable? – infinite369 Feb 20 '19 at 04:31
  • Yes. Depending on your class definition, this may need to compare contents of members as well as the value of members (look-up deep compare, or deep equality). E.g. if allData in my example is another class, you may need to implement further Equatable implementations. – Chris Shaw Feb 20 '19 at 04:38
  • Thank you, I will look into the topics you mentioned. – infinite369 Feb 20 '19 at 05:13
  • In the case of UNIT TESTING the mapping between 2 objects: I believe Equatable is not a good way of comparing 2 objects. The reason I say this is you are testing your code to compare the objects and someone can easily add a new property and not add mapping or include the comparison of the new property in the func ==(lhs function. So Equatable is likely not to compare all the properties and that defeats the purpose of comparing the 2 objects. Having said that I still can't provide a better solution. – Johan Dec 12 '22 at 12:52
-1

Did you just wanted to check for class kind, like below? similar to [custom isKindOfClass: MyClass]

guard customClass is MyClass else {
        XCTFail("FAILURE ")
        return 
    }

Edit:

Compare contents of two custom objects, check this. After implementing the custom equatable method, use the below statement to check the unit test.

XCTAssert(object1 == object2)
Jay
  • 856
  • 7
  • 17