一分钟了解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 @   ShaPherD  阅读(2426)  评论(1编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示