我有一个日期数组,我想使用 NSDateFormatter 从中获取 NSDate 对象。
let dates = [
"Tue, 04 Feb 2014 22:03:45 Z",
"Sun, 05 Jun 2016 08:35:14 Z",
"Sun, 05 Jun 2016 08:54 +0000",
"Mon, 21 Mar 2016 13:31:23 GMT",
"Sat, 04 Jun 2016 16:26:37 EDT",
"Sat, 04 Jun 2016 11:55:28 PDT",
"Sun, 5 Jun 2016 01:51:07 -0700",
"Sun, 5 Jun 2016 01:30:30 -0700",
"Thu, 02 June 2016 14:43:37 GMT",
"Sun, 5 Jun 2016 01:49:56 -0700",
"Fri, 27 May 2016 14:32:19 -0400",
"Sun, 05 Jun 2016 01:45:00 -0700",
"Sun, 05 Jun 2016 08:32:03 +0000",
"Sat, 04 Jun 2016 22:33:02 +0000",
"Sun, 05 Jun 2016 01:52:30 -0700",
"Thu, 02 Jun 2016 15:24:37 +0000"
]
我本来打算使用 GWT 模式,但像这样构建我的单元测试感觉很奇怪,因为我需要为每种情况编写十几个或更多不同的测试函数。
有人可以提出更好的方法吗?或者这是“Given、When、Then”模式的可接受用法吗?
..我真的不想有 testRFC822DateFormatter1(), testRFC822DateFormatter2(), testRFC822DateFormatter3(),...
func testRFC822DateFormatter() {
// Given
let rfc822DateFormatter = RFC822DateFormatter()
let dateString = "Tue, 04 Feb 2014 22:03:45 Z"
// When
let date = rfc822DateFormatter.dateFromString(dateString)
// Then
XCTAssertNotNil(date)
let components = NSCalendar.currentCalendar().components([.Year, .Month, .Day, .Hour, .Minute, .Second, .TimeZone, .Calendar], fromDate: date!)
XCTAssertEqual(components.day, 4)
XCTAssertEqual(components.month, 2)
XCTAssertEqual(components.year, 2014)
XCTAssertEqual(components.hour, 22)
XCTAssertEqual(components.minute, 3)
XCTAssertEqual(components.second, 45)
XCTAssertEqual(components.timeZone?.daylightSavingTimeOffset, 3600)
XCTAssertEqual(components.timeZone?.secondsFromGMT, 3600)
XCTAssertEqual(components.calendar?.calendarIdentifier, NSCalendarIdentifierGregorian)
}
谢谢!
最佳答案
您需要两种测试。
1) 确保特定日期格式与特定日期格式正常工作的测试。 2) 一项测试,以确保如果两种不同的日期格式适用于特定的日期格式,则它们要么相同,要么您的逻辑将选择正确的一个。
因此,我设想对每个 dateFormat
进行一次测试,并对可能匹配多种格式的每个日期进行一次测试。
对于这些测试,据我所知,GWT 模式很好。更重要的是确定您需要使用的所有各种日期格式并确保每个日期使用正确的日期格式。
<小时/>顺便说一句,我不愿意对 NSDateFormatter 进行子类化,我也不认为这是必要的......对于您在问题中指定的输入,下面的代码就是必需的:
let dateFormatter1: NSDateFormatter = {
let result = NSDateFormatter()
result.dateFormat = "EEE, d MMM yyyy HH:mm:ss Z"
return result
}()
let dateFormatter2: NSDateFormatter = {
let result = NSDateFormatter()
result.dateFormat = "EEE, d MMM yyyy HH:mm Z"
return result
}()
let dateFormatter3: NSDateFormatter = {
let result = NSDateFormatter()
result.dateFormat = "EEE, d MMM yyyy HH:mm:ss z"
return result
}()
func dateFromString(dateString: String) -> NSDate? {
return dateFormatter1.dateFromString(dateString) ?? dateFormatter2.dateFromString(dateString) ?? dateFormatter3.dateFromString(dateString)
}
对于上面的代码,我期望总共进行三个测试,每个日期格式化程序一个。
关于swift - 对 NSDateFormatter 进行单元测试的好方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37768009/