简体   繁体   English

比较Objective-C单元测试断言中的两个对象

[英]Compare two objects in objective-c unit test assert

I am new in Testing in Objective-C but I have some experience in .NET with MSTest. 我是Objective-C中的测试新手,但是我在.NET中具有MSTest的经验。

What is the best way to compare two objects in objective C using XCTAssert? 使用XCTAssert比较目标C中的两个对象的最佳方法是什么?

Example code is below: 示例代码如下:

- (void)testNumericValue_SaveAndLoad_ShouldSaveAndThenLoadIdenticalObject
{
    [_numericValue_1 saveToDatabaseWithKey:VALID_KEY_1];
    NumericValue *tmpNumericValue = [[NumericValue alloc] loadFromDatabaseWithKey:VALID_KEY_1];

    XCTAssertEqualObjects(tmpNumericValue, _numericValue_1);
}

- (void)testLoop_SaveAndLoad_ShouldSaveAndThenLoadIdenticalObject
{
    [_loop_1 saveToDatabase];
    Loop *tmpLoop = [[Loop alloc] loadFromDatabase];

    XCTAssertEqualObjects(tmpLoop, _loop_1);
}

I have many tests like this. 我有很多这样的测试。 I am sure that save and load functions work in a proper way. 我确信saveload功能可以正常工作。 Some of this tests are passing, some are failing. 有些测试通过了,有些失败了。 What is the reason? 是什么原因? I want this objects to have same properties values. 我希望该对象具有相同的属性值。 I have to compare all of this properties one by one? 我必须一一比较所有这些属性吗? Is there any "cleaner" way? 有什么“清洁”方法吗?

Thank you for your time 感谢您的时间

Some of them are passing, some are failing. 他们中有些人过去了,有些人失败了。 What is the reason? 是什么原因?

This is probably because you are using the default equality comparison. 这可能是因为您正在使用默认的相等比较。

I want this objects to have same properties values. 我希望该对象具有相同的属性值。 I have to compare all of this properties one by one? 我必须一一比较所有这些属性吗? Is there any "cleaner" way? 有什么“清洁”方法吗?

Yes. 是。 Override isEquals to compare properties one-by-one, and XCTAssertEqualObjects will do the comparisons correctly: 覆盖isEquals可以一对一比较属性,并且XCTAssertEqualObjects将正确进行比较:

-(BOOL)isEqual:(id)other {
     ...
}

Don't forget to override hash as well: 不要忘记也重写hash

-(NSInteger)hash {
    ...
}

Here is a link to an answer that discusses Best practices for overriding isEqual: and hash . 这里是一个答案的链接,该答案讨论了覆盖isEqual:hash最佳实践

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM