在Module / Class的末尾执行代码,比如Ruby test / unit

时间:2020-12-30 23:27:35

Ruby's unit testing framework executes unit tests even though nobody creates unit test object. For example,

Ruby的单元测试框架执行单元测试,即使没有人创建单元测试对象。例如,

in MyUnitTest.rb

require 'test/unit'

class MyUnitTest < Test::Unit::TestCase
    def test_true
        assert true
    end
end

and when i invoke that script as

当我调用该脚本时

ruby MyUnitTest.rb

test_true method gets executed automatically. How is this done?

test_true方法自动执行。这是怎么做到的?

I am trying to come up with a framework that can do similarly. I dont want "if __ FILE __ == $0" at the end of every module that uses my framework.

我试图提出一个可以做类似的框架。我不想在使用我的框架的每个模块的末尾“if __ FILE __ == $ 0”。

thanks.

2 个解决方案

#1


Test::Unit uses at_exit for this, which runs code immediately before your application quits:

Test :: Unit使用at_exit,在应用程序退出之前立即运行代码:

at_exit do
  puts "printed before quit"
end

.. other stuff

I don't think there is any way to run code specifically after a class or module definition is closed.

在关闭类或模块定义之后,我认为没有任何方法可以专门运行代码。

#2


Similar to Daniel Lucraft's answer, you could define a finalizer guard to have some code run when the garbage collector runs:

与Daniel Lucraft的答案类似,您可以定义一个终结器防护,以便在垃圾收集器运行时运行一些代码:

ObjectSpace.define_finalizer(MyClass, lambda {
  puts "printed before MyClass is removed from the Object space"
})

But personally I think at_exit is a better fit since its timing is a bit more deterministic.

但我个人认为at_exit更合适,因为它的时机更具确定性。

#1


Test::Unit uses at_exit for this, which runs code immediately before your application quits:

Test :: Unit使用at_exit,在应用程序退出之前立即运行代码:

at_exit do
  puts "printed before quit"
end

.. other stuff

I don't think there is any way to run code specifically after a class or module definition is closed.

在关闭类或模块定义之后,我认为没有任何方法可以专门运行代码。

#2


Similar to Daniel Lucraft's answer, you could define a finalizer guard to have some code run when the garbage collector runs:

与Daniel Lucraft的答案类似,您可以定义一个终结器防护,以便在垃圾收集器运行时运行一些代码:

ObjectSpace.define_finalizer(MyClass, lambda {
  puts "printed before MyClass is removed from the Object space"
})

But personally I think at_exit is a better fit since its timing is a bit more deterministic.

但我个人认为at_exit更合适,因为它的时机更具确定性。