Search code examples
objective-cocunit

STAssertEquals for checking NSArray count - clean way


What is the correct way to check the NSArray items count with STAssertEquals for NSArray.

Following was expected to work:

...
STAssertEquals(1, [myArray count], @"One item should be in array");

This code produces "Type mismatch" runtime error when running test.

Instead I have to do an explicit cast to NSUInteger:

STAssertEquals((NSUInteger)1, [myArray count], @"One item should be in array");

This works - but looks kind a ugly due to explicit cast.

I also want to avoid using STAssertTrue because STAssertEquals looks more appropriate (we compare two values) and shows the actual and expected values.

What is correct way to check it in Objective-C?

UPDATE 1

Thanks for the answers suggested to use 1u as unsigned int literal

STAssertEquals(1u, [myArray count], @"One item should be in array");

But as @Aaron mentioned it still ugly - I would like to use "1" directly - thinking on using myArray.count == 1 instead now. And the reason for it is that 1u doesn't look very clean. The 1 is 1 for me. You never write 1u in math :-) Any other suggestions?

UPDATE 2

As @H2CO3 mentioned 1u even could not always work and as suggested in some thread we could use more declarative definition for expected value which will solve the problem of casting:

NSUInteger expectedItemsCount = 1;
STAssertEquals(expectedItemsCount, [myArray count], @"One item should be in array");

I prefer it to 1u solution because it looks cleaner. But the cons of this approach is that we have extra line and code is not very compact. So it looks like we have to choose between two approaches: (NSUInteger)1 and NSUInteger expectedItemsCount = 1;


Solution

  • C's type system...

    1 is int, so it's signed. NSArray.count is NSUInteger so it's unsigned. Make the integer literal unsigned:

    STAssertEquals(myArray.count, 1u, @"+1 item needed");
    

    Edit: Even better, the above will fail on 64-bit (it would work with 1ull there), so what if you just use something like

    const NSUInteger expectedLength = 1;
    STAssertEquals(myArray.count, expectedLength, @"+1 item needed");
    

    (The thread from where I stole this...)