一分钟了解ruby中的单测

之前用gtest写过很多c++的单测case, 对gtest的强大和灵活印象深刻;最近需要用ruby写一个小工具, 接触了下ruby, 写了代码就要写单测啊(好的单测确实对代码的健壮性和正确性保证上太重要了)

简单搜了下发现 单测是ruby的一部分, 而不像c++等要引用gtest等三方库,简单可依赖,  简单写个例子

代码:

module Brtest
    class Myfile
       def write(theFile,theCont)
            _fileName=File.dirname(__FILE__)+"/tmp/"+theFile
            Dir.mkdir(File.dirname(_fileName)) unless File.exist?(File.dirname(_fileName))
            aFile = File.new(_fileName,"w")
            aFile.puts theCont
            aFile.close
       end
    end 
end

对应单测, 放在test目录下:

require "test/unit"
require File.dirname(__FILE__)+"/../file"
include Brtest

require "Watir-webdriver"
include Watir

class TestFile < Test::Unit::TestCase
   def test_write
      _file = Myfile.new
      _file.write("test_file","testcontent")
   end
   def test_write_html
      br = Watir::Browser.new :ie
      br.goto "baidu.com"
      _file = Myfile.new
      _file.write("test_file_html",br.html)
      br.close
   end
      
end 

运行结果:

这个单测其实还有个问题, 没有清理单测生成的文件; 正确的做法应该是生成了测试文件, case中检查文件的内容是否符合预期, 如果符合 就删掉, 不符合则失败。  我觉得实际使用中可以灵活处理, 比如我的目的就是验证我的代码是可用的, 而不是把case作为每次回归来使用的, 可以不严格按照要求。

另外附上常用的断言(参数msg表示测试失败时显示的消息):

assert(boolean, [msg])
assert_equal (expected, actual, [msg])
assert_not_equal (expected, actual, [msg])
assert_match (pattern, string, [msg])
assert_no_match (pattern, string, [msg])
assert_nil (object, [msg])
assert_not_nil (object, [msg])
assert_instance_of (class, object, [])
assert_kind_of (class, object, [])
assert_ralse (Exception, …) {block}
assert_nothing_ralsed (Exception, …) {block}

posted @ 2013-08-18 17:33  ShaPherD  阅读(2412)  评论(1编辑  收藏  举报