代码之家  ›  专栏  ›  技术社区  ›  philant

如何在ruby模块中包含单元测试?

  •  4
  • philant  · 技术社区  · 15 年前

    我正在尝试将模块的单元测试包含在与模块本身相同的源文件中,如下所示: Perl modulino

    #! /usr/bin/env ruby
    
    require 'test/unit'
    
    module Modulino
        def modulino_function
            return 0
        end
    end
    
    class ModulinoTest < Test::Unit::TestCase
        include Modulino
        def test_modulino_function
            assert_equal(0, modulino_function)
        end
    end
    

    现在,我可以运行执行这个源文件的单元测试了。

    但是 ,当我需要/从另一个脚本加载它们时,它们也会运行。如何避免这种情况?

    除非不鼓励使用Ruby,否则有没有更惯用的方法来实现这一点?

    4 回复  |  直到 13 年前
        1
  •  13
  •   samg    15 年前

    就我个人而言,我从未听说过有人试图用Ruby做这件事。这绝对不是一个标准的做法。也就是说,您可以利用此技巧:

    if __FILE__ == $0
      # Do something.. run tests, call a method, etc. We're direct.
    end
    

    中的代码 if 块仅在文件直接执行时执行,而不是在其他库或应用程序需要时执行。

    这里有更多ruby技巧: http://www.rubyinside.com/21-ruby-tricks-902.html

        2
  •  3
  •   Community CDub    8 年前

    this post

    因此,单元测试可能应该存在于类文件中,或者如果您只需要一般可用的方法,那么可以使用类函数而不是模块。

        3
  •  3
  •   Zack Xu    11 年前

    试试这个例子:

    class Foo < String
    end
    
    if $0 == __FILE__
        require 'minitest/autorun'
        require 'minitest/pride'
    
        class FooTest < MiniTest::Unit::TestCase
            def test_foo_instantiation
                foo = Foo.new()
                assert_instance_of Foo, foo
            end
    
            def test_foo_parent_class
                foo = Foo.new()
                assert_kind_of String, foo
            end
        end
    end
    

    然后我创建了两个单元测试。在第一个测试中,我检查是否可以实例化 Foo类的对象。在第二个测试中,我检查类Foo的实例化对象是否是一种字符串。

    如果此代码写在名为foo.rb的文件中,我可以使用以下命令运行测试:

    ruby foo.rb
    

    Minitest执行起来很快。“pride”模块允许您以彩色字体输出测试结果,这很好看。

        4
  •  1
  •   philant    15 年前

    unit.rb 在里面 .../lib/ruby/1.8/test/ 使成为现实。

    结合samg技巧(再次感谢),我们可以写:

    if (__FILE__ != $0)
        Test::Unit.run = true  ### do not run the unit tests
    end