如何对时区进行单元测试?
我想知道如何测试时区逻辑?对我来说,我的时区内容用于过滤数据库中的数据(当然在单元测试中会被模拟而不是测试)。
但我想测试它周围的逻辑,看看我是否给出了某些时间,以便它能够正确转换。
但我不知道该怎么做。
I am wondering how to you test TimeZone logic? For me my timezone stuff is used to filter data from the database(what of course in unit tests gets mocked up and not tested).
But I would like to test the logic around it to see if I give certain times in that it would be converted right.
I am not sure how to do this though.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
目前还不完全清楚你的意思。
您使用系统当前的时区吗?如果是这样,我建议您包含某种中间静态属性,该属性可以仅在测试时重置,以便您“假装”在测试期间处于不同的时区。不可否认,这意味着您必须始终谨慎使用该属性。
我敢说有一个 Win32 系统调用可以用来更改系统时区,但这听起来有点激烈 - 遗憾的是没有像文化那样知道线程的当前时区:((有
TimeZoneInfo.Local
,但据我所知,没有托管方法可以更改它。)如果您不使用本地时区,只需确保您的 API 获取您需要的所有信息编写测试,这样您就可以确保如果您处理特定时区的日期和时间,您会得到正确的答案,如果这对您有用,我可以特别想出一些好的极端情况来进行测试。有些时区每年没有一次当地午夜(夏令时停止时),这可能会搞砸某些情况。
It's not entirely clear what you mean.
Do you use the current time zone of the system? If so, I suggest you include some sort of intermediary static property which can be reset just for tests to let you "pretend" that you're in a different time zone just for the duration of a test. Admittedly it means you have to be scrupulous about always using that property.
I dare say there's a Win32 system call you could use to change the system time zone, but that sounds a bit drastic - it's a shame there's no idea of the current time zone of a thread like there is for cultures :( (There's
TimeZoneInfo.Local
, but there's no managed way of changing that, as far as I've seen.)If you're not using the local time zone, just make sure that your API takes all the information you need to write tests, so you can make sure that if you process dates and times in particular time zones, you get the right answer. If it would be useful to you, I can think up some good corner cases to test against. In particular, there are time zones where there's no local midnight once a year (when daylight savings stops) which can screw up some cases.
编辑:另一种选择是使用构造函数注入将时区传递到您的类中:
EDIT: Another alternative would be to use constructor injection to pass a time zone into your class: