Question

I was trying to write a unit test for a library. A method from library returns string and I wanted to make sure it returns right string. But somewhat STAssertEquals macro in SenTestKit saw it as different value even though it was same.enter image description here

You can see that description part clearly showed that two string values are same, yet this macro complained their values are different. When I return static string from method ( just like return @"op_user") it passed the test case. Anyone have an idea what cause to fail this test with same string value?

Was it helpful?

Solution

I think you want to use STAssertEqualObjects() instead of STAssertEquals(). The former is for Objective-C instances, the latter for primitive types.

From the docs:

STAssertEqualObjects

Fails the test case when two objects are different.

STAssertEquals

Fails the test case when two values are different.

If you compare Objective-C objects with STAssertEquals(), you're just comparing their pointer values. They could point to two different string objects that contain the same string. You would want them to compare as equal, even if their pointer values are different.

To compare the actual string contents, you'd use the isEqual: method, which is exactly what STAssertEqualObjects() does.

OTHER TIPS

Not quite an answer (since Marc already replied correctly), but as a general rule, never ever use STAssertEquals!

It uses a questionable approach which first checks whether the types of the arguments are equal, using @encode to determine the type, and then basically performs a memcmp. So, variables defined as below

int i = 1; 
unsigned int ui = 1;
assert(i == ui);
STAssertEquals(i, ui, @"");

will let STAssertEquals fail - even though the values are equal.

While

signed char sc = 1;
char c = 1;
STAssertEquals(sc, c, @"");

guess what?
(Hint: types are NOT equal!)

... will succeed, because @encode cannot differentiate between an unsigned char and an signed char, which however are distinct types!

Other issues are with padding in structs where memcmp may return non-zero but the struct values would actually compare equal.

So better don't use STAssertEquals, and as well its successor XCTAssertEqual which adopted the same ridiculous approach.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top