在 ocUnit 中比较 NSArray
我是 ocUnit 的新手,我正在尝试使用 STAssertTrue 方法和 == 比较 2 个数组是否相等。
下面的测试只是向被测系统(sut)询问返回的数组
- (void) testParse {
SomeClassForTesting* sut = [[SomeClassForTesting alloc] init];
NSArray* result = [sut parseAndReturn];
NSArray* expected = [[NSArray alloc] initWithObjects:@"1", @"2", @"3", @"4",nil];
STAssertTrue(result == expected, @"This test failed");
}
然后在我的生产代码中我只是返回相同的数组
- (NSArray *)parseAndReturn
{
NSArray* x = [[NSArray alloc] initWithObjects:@"1", @"2", @"3", @"4",nil];
return x;
}
但是当测试运行时我会失败。我应该如何比较这些对象来看看它们是否相同?
先感谢您
I'm new to ocUnit and I'm attempting to compare 2 arrays with the STAssertTrue method and == for equality.
The test below simply asks the system under test (sut) for the array in return
- (void) testParse {
SomeClassForTesting* sut = [[SomeClassForTesting alloc] init];
NSArray* result = [sut parseAndReturn];
NSArray* expected = [[NSArray alloc] initWithObjects:@"1", @"2", @"3", @"4",nil];
STAssertTrue(result == expected, @"This test failed");
}
Then inside my production code I simply return the same array
- (NSArray *)parseAndReturn
{
NSArray* x = [[NSArray alloc] initWithObjects:@"1", @"2", @"3", @"4",nil];
return x;
}
Yet when the test runs I get a failure. How should I compare these objects to see if they are the same or not?
Thank you in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有一个宏
STAssertEqualObjects
,它使用-isEqual:
进行对象比较。我认为这正是您所需要的。在您的情况下,
STAssertTrue
比较对象指针并失败,因为result
和expected
是不同对象(它们的指针不同) 。There's a macro
STAssertEqualObjects
which uses-isEqual:
for object comparison. I think it's exactly what you need.STAssertTrue
in your case compares object pointers and fails becauseresult
andexpected
are different objects (their pointers are different).您可能想要类似的东西:
这将遍历数组,如果每个项目没有从其 isEqual 实现返回 true,则返回 false。如果您的数组成员是 NSString(如所示),那么您应该可以开始了。
正如另一位朋友所说,在 Objective-C 中,== 意味着指针相等,而不是值相等。
You probably want something like:
This will go through the arrays and return false if each item does not return true from its isEqual implementations. If your array members are NSStrings as is indicated, you should be good to go.
As the other fellow said, in Objective-C, == implies pointer equality and not value equivalence.
您要比较的是 expected 和 result 是否指向同一个数组,而它们显然不是。相反,为了比较内容,您需要遍历 NSArray 并使用对象的比较函数逐个对象进行比较。
What you are comparing is whether expected and result are pointing to the same array, which they obviously are not. Instead in order to compare the content you need to go through both the NSArrays and compare object by object using the object's compare function.