2013-02-15 73 views
1

当我在做单元测试的,我不相信非常多的代码,我会经常使用此模式:如何批量单元测试Ruby中的对象集合?

  1. 想起来了许多(也许是几十个)的期望我有输出我函数(我认为这些是关于代码如何工作的“理论”)。
  2. 旋转数以千计的物体。
  3. 通过我编写的几十个断言运行每个对象,反映了我对代码工作方式的期望。

在Ruby的Test ::股(到我新),我一直在做这样的事情:

class TestFooBarrer < Test::Unit::TestCase 
    def setup 
    @lots_of_objects_to_be_tested = FooBarrer.bar_lots_of_foos 
    end 

    def assert_foo_has_been_barred(foo) 
    assert_kind_of Bar, foo 
    end 

    def assert_foo_has_baz_method(foo) 
    assert_respond_to foo, :baz 
    end 

    #Many more assertions along those lines go here. 

    def test_all_theories 
    @lots_of_objects_to_be_tested.each do |foo| 
     assert_foo_has_been_barred(foo) 
     assert_foo_has_baz_method(foo) 
     # etc. 
     # 
    end 
    end 
end 

这显然变得有点笨拙,当理论的数我测试是在几十个,并涉及什么看起来像我很多不必要的重复。我更愿意做这样的事情:

class FooTheories 
    def self.assert_all_theories(foo) 
    # ??? 
    end 

    def assert_foo_has_been_barred(foo) 
    assert_kind_of Bar, foo 
    end 

    def assert_foo_has_baz_method(foo) 
    assert_respond_to foo, :baz 
    end 

    #Many more assertions along those lines go here. 
end 


class TestFooBarrer < Test::Unit::TestCase 
    def setup 
    @lots_of_objects_to_be_tested = FooBarrer.bar_lots_of_foos 
    end 

    def test_all_theories 
    @lots_of_objects_to_be_tested.each do |foo| 
     FooTheories.assert_all_theories(foo) 
    end 
    end 
end 

基本上,我正在寻找一种方式来写一堆断言在一个地方,然后一遍又一遍给他们打电话的对象量大。

在Ruby中有类似的东西吗?我不特别与Test :: Unit绑定。任何测试框架都很好。

+0

哦,请不要使用“理论”,甚至在报价:( – 2013-02-15 18:18:52

+0

“假设”会多给点,但很难键入:) – 2013-02-15 18:20:10

回答

1

我会做的是在飞行中生成测试。在test_helper添加一个方法:

def test(obj, &block) 
    define_method("test_#{ obj.to_s }", &block) 
end 

然后你就可以让你的测试套件像下面

class TestObjects < Test::Unit::TestCase 

    @objects_to_test = [...] 

    @objects_to_test.each do |obj| 
    test obj do 

     assert obj.is_a?(Foo), 'not a foo' 

     # all assertions here 

    end 
    end 

end 

然后,如果失败的话,你会得到知道哪些对象失败,因为名称的测试是对象的字符串表示。防爆消息:

1) Failure: 
test_#<Bar:0x000001009ee930>(TestObjects): 
not a foo 
+0

工作就像一个魅力,谢谢!我认为有一些元编程解决方案。 – 2013-02-15 21:10:39