In Ruby's Test::Unit::TestCase, how do I override the initialize method?

前端 未结 10 1845
再見小時候
再見小時候 2020-12-07 14:54

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 M         


        
10条回答
  •  误落风尘
    2020-12-07 15:23

    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
    

    Here is an example:

    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
    

提交回复
热议问题