简体   繁体   English

如何在Perl中调用localtime()的单元测试函数?

[英]How to unit test functions calling localtime() in Perl?

I have a method calling localtime that I wrote a unit test for. 我有一个调用localtime的方法,我写了一个单元测试。 I seed the call to localtime in my test so that I know the expected answers. 我在测试中将调用播种到localtime ,以便我知道预期的答案。 So far, so good. 到现在为止还挺好。 I happen to run the unit test on a machine in a different timezone and, predictably, the tests fail, because they're some # of hours off. 我碰巧在不同时区的机器上运行单元测试,并且可以预见,测试失败了,因为他们有几个小时的休息时间。 I suppose I could dynamically determine the correct expected values but that seems to go against the idea of knowing the answer before asking the question. 我想我可以动态地确定正确的预期值,但这似乎违背了在提出问题之前知道答案的想法。

Any thoughts on how to approach this? 有关如何处理此问题的任何想法? Override localtime ? 覆盖localtime That seems extreme. 这看起来很极端。

Thanks! 谢谢!

I don't think there's any problem with calculating the values of answers in a unit test. 我不认为在单元测试中计算答案的值有任何问题。 Unit tests should be simple enough to avoid complexity-related bugs, but a simple time zone calculation probably doesn't cross the line. 单元测试应该足够简单,以避免与复杂性相关的错误,但简单的时区计算可能不会跨越线。

In this particular case, though, you could set the time zone to a fixed value (or several) as part of the test. 但是,在这种特殊情况下,您可以将时区设置为固定值(或几个)作为测试的一部分。 See this Stack Overflow post about setting time zone in Perl . 请参阅此Stack Overflow帖子,了解有关在Perl中设置时区的信息

我不知道你的要求是什么,但你也许可以得到的东西做使用测试:: MockTime时间::模拟 ,这两种产品将取代localtime和朋友与行为,但是你想他们嘲笑的版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM