【发布时间】:2016-06-11 19:58:22
【问题描述】:
我有一个日期数组,我想使用 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 模式,但我觉得像这样构建我的单元测试很奇怪,因为我需要为每个案例编写十几个或更多不同的测试函数。
任何人都可以提出更好的方法吗?或者这是“给定,何时,然后”模式的可接受用法?
..我真的不想有 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)
}
谢谢!
【问题讨论】:
-
我很好奇你为什么要编写自己的日期格式化程序而不是只使用
NSDateFormatter? -
我是,它实际上是 NSDateFormatter 的子类。我事先不知道格式可能是什么,只知道它符合 3 个可能的 RFC 规范中的 1 个,不幸的是,它需要与上面的一个(RFC822)松散。
-
我假设字符串数组只是一个代表性样本? (否则,您可以只创建一个 NSDates 数组并完成它。)
-
我还不能称之为代表。我将与 700 多个不同的日期源集成。我需要测试它如何根据规范中的几种不同日期格式来解释字符串日期。就像我说的,不幸的是,我还需要在规范上松散一些。仅从 stringFromDate 方法获取 NSDate 对象并不能保证我正确理解了日期。
-
无论如何,我才刚刚开始进行单元测试。还没有多少经验,也许写很多类似的函数其实是一个完全没问题的方法……
标签: swift unit-testing xctest