我正在编写一些测试来查看人员对象是否正确保存到本地数据库(SQLite,使用字符串作为日期)。
在我的测试中我有:
let testPerson = Person(firstName:"John", lastName:"Doe")
保存到数据库后我测试是否 createdAt != nil
没关系!然后:
let testPerson2 = Person.LoadByID(testPerson.id)
这是一个静态函数,将 person 对象从数据库加载到 testPerson2
所有字段都通过了测试(因此除了 createdAt 和 updateAt 日期外,testPerson 和 testPerson2 完全相同
如果我对这些日期进行 println,它们将完全相同:
testPerson.createdAt : Optional(2015-08-14 12:03:01 +0000)
testPerson2.createdAt :Optional(2015-08-14 12:03:01 +0000)
但是测试(通过两种不同的方法):
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 成功
为什么? Println 并查看数据库本身看起来没问题。
最佳答案
NSDate 在内部至少有一个纳秒的分辨率。您的 dateFormatter 删除了大部分分辨率,因为 dateformat ss.SSS
仅处理毫秒。
如果您不需要纳秒精度,我建议您只检查毫秒级别的日期。为此,我通常使用 XCTAssertEqualWithAccuracy()
。
例如:
XCTAssertEqualWithAccuracy(date1.timeIntervalSinceReferenceDate,
date2.timeIntervalSinceReferenceDate,
0.001,
"")
关于swift - NSDate 在测试中比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32009877/