2

I'm writing iOS unit tests for the first time and I'm having some trouble. When I write unit tests in PHP, I can also assert that the returned value of a function is - let's say - an array.

The code below worked, but that might not be the best way to do this, since the content of the array might change.

NSArray *first = [Example getArray];
NSArray *second = @[@"test", @"test2"];

XCTAssertEqualObjects(first, second, @"Example:getArray doesn't return an array.");

What's the proper way to do this in Objective-C?

user4992124
  • 1,574
  • 1
  • 17
  • 35

3 Answers3

2

To test if the method returns a particular class, you can use isKindOfClass to test the type of object.

XCTAssertTrue([first isKindOfClass:[NSArray class]], @"...");

If you also want to test the contents of the array, then you have some options.

  • You can sort the contents of the arrays so that both arrays have the same order. See this SO post on different ways to sort arrays.

    // let's say your arrays contains objects that have a name property 
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
    NSArray *sortedFirst = [first sortedArrayUsingDescriptors];
    NSArray *sortedFirst = [first sortedArrayUsingDescriptors];
    XCTAssertEqualObjects(sortedFirst, sortedSecond, @"...");
    
  • You can create an NSSet with the array. With an NSSet, equality will only look at whether you have the same objects in the set, not the order in which they appear. This will only work with arrays that will never contain duplicate objects. If create a set from an array that has duplicate objects, only one instance of those objects will be in the set.

    NSSet *firstSet = [NSSet setWithArray:first];
    NSSet *secondSet = [NSSet setWithArray:second];
    XCTAssertEqualObjects(firstSet, secondSet, @"...");
    
  • You can compare the number of objects in the array. This isn't a very granular test, but it gives you more granular testing than just comparing types.

    XCTAssertEqual(first.count, second.count, @"...");
    
Community
  • 1
  • 1
keithbhunter
  • 12,258
  • 4
  • 33
  • 58
0

Simply put:

XTCAssert([first isKindOfClass:[NSArray class]], @"First isn't an array");
John Farkerson
  • 2,543
  • 2
  • 23
  • 33
0

Just check the class of your returned object, like this:

XCTAssertTrue([first isKindOfClass:[NSArray class]], @"Example:getArray doesn't return an array.");

Also you can check array.count, or if it contains certain object with containsObject: method.

wirrwarr
  • 265
  • 1
  • 14