单位测试代码获取当前时间 [英] Unit testing code which gets current time
问题描述
为获取当前时间的代码编写单元测试的最佳方式是什么?例如,一些对象可能只在工作日创建,其他对象考虑当前检查执行某些操作的时间等等。
What is the best way to write unit test for code which gets current time? For example some object might be created only at business days, other objects take into account current time when checking permissions to execute some actions, etc.
我想我应该模拟Date.today和Time.now。这是正确的方法吗?
I guess that I should mock up the Date.today and and Time.now. Is this right approach?
更新:两个解决方案(a)Time.is和(b)Time.stubs(:now).returns(t)工作。 (a)是非常好的方法,但(b)解决方案将与其他测试代码更一致。
Update: Both solutions (a) Time.is and (b) Time.stubs(:now).returns(t) work. (a) is very nice approach but (b) solution will be more consistent with other test code.
在这个问题作者要求一般解决方案。对于Ruby,根据我的选择,上述两个解决方案是更简单的,因此比提取代码更好约会时间。
At this question an author asks for a general solution. For Ruby, in my option two above solutions are simpler and therefore better than extracting code which gets current date / time.
BTW我建议您使用慢性获取所需时间,例如
BTW I recommend to use Chronic to get required time, e.g.
require 'Chronic'
mon = Chronic.parse("next week monday")
Time.stubs(:now).returns(mon)
推荐答案
Time.now或Date.today看起来很简单,看起来就像:
Mocking Time.now or Date.today seems straightforward enough, would look something like:
require 'rubygems'
require 'test/unit'
require 'mocha'
class MyClass
def foo
Time.now
end
end
class MyTest < Test::Unit::TestCase
def test_foo
assert true
t = Time.now
Time.expects(:now).returns(t)
assert_equal t, MyClass.new.foo
end
end
这篇关于单位测试代码获取当前时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!