以前用gtest写过不少c++的单测case, 对gtest的强大和灵活印象深入;最近须要用ruby写一个小工具, 接触了下ruby, 写了代码就要写单测啊(好的单测确实对代码的健壮性和正确性保证上过重要了)html
简单搜了下发现 单测是ruby的一部分, 而不像c++等要引用gtest等三方库,简单可依赖, 简单写个例子c++
代码:web
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目录下:ruby
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
运行结果:less
这个单测其实还有个问题, 没有清理单测生成的文件; 正确的作法应该是生成了测试文件, 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}ui