之前用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}