Objective c XCTASERTEQUAL不适用于双值

Objective c XCTASERTEQUAL不适用于双值,objective-c,unit-testing,Objective C,Unit Testing,我正在为我正在编写的映射坐标函数编写一些单元测试。不幸的是,XCTest出现了一些我无法确定的问题,导致我的测试失败: NSString *testValue = @"121°31'40\"E"; double returnValue = coordinateStringToDecimal(testValue); static double expectedValue = 121.5277777777778; XCTAssertEqual(returnValue, expectedValue,

我正在为我正在编写的映射坐标函数编写一些单元测试。不幸的是,XCTest出现了一些我无法确定的问题,导致我的测试失败:

NSString *testValue = @"121°31'40\"E";

double returnValue = coordinateStringToDecimal(testValue);
static double expectedValue = 121.5277777777778;
XCTAssertEqual(returnValue, expectedValue, @"Expected %f, got %f", expectedValue, returnValue);
我读这篇文章是为了解决问题。但是,我能够验证数字和类型是否相同。以下是检查每个值类型的控制台输出:

(lldb) print @encode(__typeof__(returnValue))
(const char [2]) $5 = "d"
(lldb) print @encode(__typeof__(expectedValue))
(const char [2]) $6 = "d"
调试器中的变量视图显示它们是相同的:

有趣的是在lldb中比较它们的控制台输出:

(lldb) print (returnValue == expectedValue)
(bool) $7 = false

类型相同,实际数量相同。否则我的断言为什么会失败呢?

因为您处理的是浮点数,所以总是会有一定程度的不准确,即使是在
双值之间。在这些情况下,您需要使用不同的断言:
xctasertequalwithaccurity
。从文档中:

当a1在+或-精度范围内不等于a2时,生成故障。此测试适用于浮点和双精度等标量,其中微小的差异可能会使这些项不完全相等,但适用于所有标量

将断言更改为以下内容:

XCTAssertEqualWithAccuracy(returnValue, expectedValue, 0.000000001);
或在Swift 4中:

XCTAssertEqual(returnValue, expectedValue, accuracy: 0.000000001, "expected better from you")
敏捷地:

expect(expectedValue).to(beCloseTo(returnValue, within: 0.000000001))

在Swift 4中,从函数名中删除了精度-现在它的XCTAssertEqual重载:

XCTAssertEqual(returnValue, expectedValue, accuracy: 0.000000001, "expected better from you")

在swift 3中,添加了一个
accurity
参数标签:
xctasertequalwithaccurity(返回值,期望值,精度:0.000000001,“期望您更好”)
现在看起来好像只有一个重载的
xctasertequal
允许一个
accurity
参数,就像
xctasertequalwithaccurity
那样。使用
.ulpOfOne
代替一些静态浮点值,这相当于
FLT/DBL\u EPSILON