XCTAssertEqual 不适用于双精度值 [英] XCTAssertEqual not working for double values
问题描述
我正在为我正在编写的地图坐标函数编写一些单元测试.不幸的是,XCTest 发生了一些我无法确定的事情,导致我的测试失败:
I am writing some unit tests for a map coordinate function that I am writing. Unfortunately, there's something going on with XCTest that I am unable to nail down that is causing my test to fail:
NSString *testValue = @"121°31'40\"E";
double returnValue = coordinateStringToDecimal(testValue);
static double expectedValue = 121.5277777777778;
XCTAssertEqual(returnValue, expectedValue, @"Expected %f, got %f", expectedValue, returnValue);
我确实阅读了这个类似问题来解决问题.但是,我能够验证数字和类型是否相同.这是检查每个值的类型的控制台输出:
I did read this similar question to troubleshoot. However, I am able to validate that the numbers and types are the same. Here is the console output of checking the type of each value:
(lldb) print @encode(__typeof__(returnValue))
(const char [2]) $5 = "d"
(lldb) print @encode(__typeof__(expectedValue))
(const char [2]) $6 = "d"
调试器中的变量视图显示它们是相同的:
The Variables View in the debugger is showing them to be the same:
有趣的是在 lldb 中比较它们的控制台输出:
The interesting thing is the console output of comparing them in lldb:
(lldb) print (returnValue == expectedValue)
(bool) $7 = false
类型相同,实际数量相同.为什么我的断言会失败???
The types are the same and the actual numbers are the same. Why else would my assert be failing???
推荐答案
因为你在处理浮点数,所以总会有一定程度的不准确,即使在 double
值之间.在这些情况下,您需要使用不同的断言:XCTAssertEqualWithAccuracy
.来自文档:
Because you are dealing with floating point numbers, there will always be a certain degree of inaccuracy, even between double
values. In these cases, you need to use a different assertion: XCTAssertEqualWithAccuracy
. From the docs:
当 a1 在 + 或 - 精度范围内不等于 a2 时,生成失败.此测试适用于浮点数和双精度数等标量,其中微小的差异可能会使这些项目不完全相等,但适用于所有标量.
Generates a failure when a1 is not equal to a2 within + or - accuracy. This test is for scalars such as floats and doubles, where small differences could make these items not exactly equal, but works for all scalars.
把你的断言改成这样:
XCTAssertEqualWithAccuracy(returnValue, expectedValue, 0.000000001);
或者在 Swift 4 中:
Or in Swift 4:
XCTAssertEqual(returnValue, expectedValue, accuracy: 0.000000001, "expected better from you")
在敏捷中:
expect(expectedValue).to(beCloseTo(returnValue, within: 0.000000001))
这篇关于XCTAssertEqual 不适用于双精度值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!