在 Ruby 的 Test::Unit::TestCase 中,如何覆盖 initialize 方法? [英] In Ruby's Test::Unit::TestCase, how do I override the initialize method?

查看:31
本文介绍了在 Ruby 的 Test::Unit::TestCase 中,如何覆盖 initialize 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 Test::Unit 苦苦挣扎.当我想到单元测试时,我会想到每个文件一个简单的测试.但是在 Ruby 的框架中,我必须改为这样写:

I'm struggling with Test::Unit. When I think of unit tests, I think of one simple test per file. But in Ruby's framework, I must instead write:

class MyTest < Test::Unit::TestCase 
   def setup 
   end

   def test_1 
   end

   def test_1 
   end
end

但是每次调用 test_* 方法都会运行 setup 和 teardown.这正是我不想要的.相反,我想要一个只为整个班级运行一次的设置方法.但是我似乎无法在不破坏 TestCase 的初始化的情况下编写自己的 initialize().

But setup and teardown run for every invocation of a test_* method. This is exactly what I don't want. Rather, I want a setup method that runs just once for the whole class. But I can't seem to write my own initialize() without breaking TestCase's initialize.

这可能吗?还是我让这一切变得非常复杂?

Is that possible? Or am I making this hopelessly complicated?

推荐答案

如 Hal Fulton 的书The Ruby Way"中所述.他覆盖了 Test::Unit 的 self.suite 方法,该方法允许类中的测试用例作为套件运行.

As mentioned in Hal Fulton's book "The Ruby Way". He overrides the self.suite method of Test::Unit which allows the test cases in a class to run as a suite.

def self.suite
    mysuite = super
    def mysuite.run(*args)
      MyTest.startup()
      super
      MyTest.shutdown()
    end
    mysuite
end

这是一个例子:

class MyTest < Test::Unit::TestCase
    class << self
        def startup
            puts 'runs only once at start'
        end
        def shutdown
            puts 'runs only once at end'
        end
        def suite
            mysuite = super
            def mysuite.run(*args)
              MyTest.startup()
              super
              MyTest.shutdown()
            end
            mysuite
        end
    end

    def setup
        puts 'runs before each test'
    end
    def teardown
        puts 'runs after each test'
    end 
    def test_stuff
        assert(true)
    end
end

这篇关于在 Ruby 的 Test::Unit::TestCase 中,如何覆盖 initialize 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆