如何测试内部有NSDate()调用的方法?

时间:2015-06-12 07:46:29

标签: ios swift unit-testing nsdate

extension NSDate {
    class func todayDateFromMidnightForSeconds(seconds: NSTimeInterval) -> NSDate {
        let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
        let startOfTheCurrentDay = calendar.startOfDayForDate(NSDate())

        return startOfTheCurrentDay.dateByAddingTimeInterval(seconds)
    }
}

如何在自定义方法中模拟我的NSDate()以正确方式对其进行测试?

1 个答案:

答案 0 :(得分:1)

你只需要删除" class"从您的方法声明并将NSDate()替换为self,如下所示:

extension NSDate {
    func dateFromMidnightForSeconds(seconds: NSTimeInterval) -> NSDate {
        return NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!.startOfDayForDate(self).dateByAddingTimeInterval(seconds)
    }
}

NSDate().dateFromMidnightForSeconds(60)  // "Jun 12, 2015, 12:01 AM"