簡體   English   中英

在Module / Class的末尾執行代碼,比如Ruby test / unit

[英]Execute code at end of Module/Class, like Ruby test/unit

Ruby的單元測試框架執行單元測試,即使沒有人創建單元測試對象。 例如,

在MyUnitTest.rb中

require 'test/unit'

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

當我調用該腳本時

ruby MyUnitTest.rb

test_true方法自動執行。 這是怎么做到的?

我試圖提出一個可以做類似的框架。 我不想在使用我的框架的每個模塊的末尾“if __ FILE __ == $ 0”。

謝謝。

Test::Unit使用at_exit ,在應用程序退出之前立即運行代碼:

at_exit do
  puts "printed before quit"
end

.. other stuff

在關閉類或模塊定義之后,我認為沒有任何方法可以專門運行代碼。

Daniel Lucraft的答案類似,您可以定義一個終結器防護,以便在垃圾收集器運行時運行一些代碼:

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

但我個人認為at_exit更合適,因為它的時機更具確定性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM