How can I test the method that has NSDate() call inside?

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

        return startOfTheCurrentDay.dateByAddingTimeInterval(seconds)
    }
}

How can I mock my NSDate() inside my custom method to test it in a proper way?

1

There are 1 answers

1
Leo Dabus On BEST ANSWER

You just need to delete "class" declaration from your method and replace NSDate() with self as follow:

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

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