gpt4 book ai didi

ios - 比较 objective-c 单元测试断言中的两个对象

转载 作者:行者123 更新时间:2023-11-28 21:55:20 24 4
gpt4 key购买 nike

我是 Objective-C 测试的新手,但我在 .NET 和 MSTest 方面有一些经验。

使用 XCTAssert 比较 Objective-C 中的两个对象的最佳方法是什么?

示例代码如下:

- (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);
}

我有很多这样的测试。我确信 saveload 函数以正确的方式工作。一些测试通过了,一些测试失败了。是什么原因?我希望这些对象具有相同的属性值。我必须一一比较所有这些属性吗?有什么“更清洁”的方法吗?

谢谢你的时间

最佳答案

Some of them 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?

是的。覆盖 isEquals 以逐一比较属性,XCTAssertEqualObjects 将正确进行比较:

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

不要忘记重写 hash:

-(NSInteger)hash {
...
}

这是一个指向 answer that discusses Best practices for overriding isEqual: and hash 的链接.

关于ios - 比较 objective-c 单元测试断言中的两个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26808318/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com