一分钟了解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}

目录
相关文章
|
2月前
|
Ruby
|
2月前
|
Ruby
|
1月前
|
数据采集 Web App开发 数据处理
Ruby网络爬虫教程:从入门到精通下载图片
Ruby网络爬虫教程:从入门到精通下载图片
|
2月前
|
JSON 数据格式 Ruby
|
2月前
|
JSON Ubuntu Linux
|
2月前
|
存储 JSON 数据格式
|
2月前
|
安全 Ruby
|
2月前
|
调度 Ruby
|
2月前
|
人工智能 BI 计算机视觉
|
2月前
|
Ruby