我正在编写一些测试来查看person对象是否正确保存到本地数据库(SQLite,使用日期的字符串)。
在我的测试中我有:
let testPerson = Person(firstName:"John", lastName:"Doe")
保存到数据库后,我测试了createdAt!= nil
没关系!然后:
let testPerson2 = Person.LoadByID(testPerson.id)
这是一个静态函数,将数据库中的person对象加载到testPerson2
中所有字段都在测试中传递(因此对于testPerson和testPerson2它们完全相同,但createdAt和updateAt日期除外
如果我对这些日期进行了打印,那么它们就完全相同了:
testPerson.createdAt : Optional(2015-08-14 12:03:01 +0000)
testPerson2.createdAt :Optional(2015-08-14 12:03:01 +0000)
但是测试(通过2种不同的方法):
XCTAssert(testPerson2.createdAt == testPerson.createdAt, "createdAt should be the same")
或
XCTAssertTrue(testPerson2.createdAt!.isEqualToDate(testPerson2.createdAt!), "createdAt should be the same")
失败
使用2x testPerson或testPerson2进行这些测试,成功
我也尝试了以下代码:
if testPerson.createdAt!.compare(testPerson.createdAt!) == NSComparisonResult.OrderedDescending
{
println("date1 after date2");
} else if testPerson.createdAt!.compare(testPerson.createdAt!) == NSComparisonResult.OrderedAscending
{
println("date1 before date2");
} else
{
println("dates are equal");
}
如果我使用testPerson和testPerson2失败,则使用testPerson / testPerson和testPerson2 / testPerson2
为什么?打印并查看数据库本身看起来不错。
答案 0 :(得分:4)
内部NSDate的分辨率至少为1纳秒。你的dateFormatter删除了大部分分辨率,因为dateformat ss.SSS
只处理毫秒。
如果您不需要纳秒精度,我建议您只检查您的日期,直到毫秒级别。我通常会使用XCTAssertEqualWithAccuracy()
。
e.g:
XCTAssertEqualWithAccuracy(date1.timeIntervalSinceReferenceDate,
date2.timeIntervalSinceReferenceDate,
0.001,
"")