使NSTimeZone在单元测试中无故障 [英] Making NSTimeZone Trouble Free in Unit Tests
问题描述
似乎是一个简单的方法来告诉它给dst打开的时区?
我正在考虑做一个类别,以便我拦截时区调用,但这听起来很凌乱,因为我不知道你正在操作的日期。
当然,我可以写所有的测试来检查时区设置,然后只是转移了我所有的期望,但这听起来像是所有可能的最糟糕的选择。
区域特定的时区必须考虑到日光节省时间以准确计算两个日期(和时间)之间的间隔。如果您对此不感兴趣,也许您可以使用UTC时区
例如,新西兰标准时间定义为UTC + 12:00,新西兰夏令时被定义为UTC + 13:00。虽然新西兰当地时间在夏令时间有所不同,但UTC + 12:00的时间保持不变(也就是说,使用UTC + 12:00的其他国家也不会因为夏令时而神奇地前进在新西兰开始)
您可以通过提供UTC偏移量作为名称来实现:
NSTimeZone * utc_plus12 = [NSTimeZone timeZoneWithName:@UTC + 12:00];
了解您所在地区夏令时的UTC偏移量,并使用它。
So here's the problem with doing unit tests of calendar code in Objective-C: the Timezone contains the information about daylight savings, so you write a test in the summer, expecting sunrise on June 10th to occur at 6:02 am. Your test passes, later, you are running the test when it's not DST and you get a failure, because when you get the timezone, daylightsavings is turned off.
There doesn't seem to be a simple way to just tell it to give you the timezone with dst turned on?
I was thinking about doing a category so that I would intercept the timezone call but that sounds super messy as I don't know what date you are manipulating.
Of course, I could write all my tests to check the timezone setting and then just shift all my expectations but that sounds like the worst of all possible choices.
Region-specific timezones must take into account daylight saving time in order to accurately calculate intervals between two dates (and times). If you aren't interested in this, perhaps you could use a UTC “timezone” instead, which don't change at all.
For example, New Zealand Standard Time is defined as UTC+12:00, and New Zealand Daylight Saving Time is defined as UTC+13:00. Although the local time in New Zealand differs during Daylight Saving Time, the times in UTC+12:00 remain the same (that is, every other country that also uses UTC+12:00 don't magically move forward just because Daylight Saving Time has commenced in New Zealand).
You can achieve this simply by providing that UTC offset as the name:
NSTimeZone *utc_plus12 = [NSTimeZone timeZoneWithName:@"UTC+12:00"];
Find out what UTC offset your region's daylight saving time is based on and use that.
这篇关于使NSTimeZone在单元测试中无故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!