Ruby中也提供了单元测试的框架,类似Java中的JUnit,此框架在Ruby中被成为mini test。
我们先看一个例子,这个是我的源代码:
require 'json' module PMU_INTERFACE class IUserLoginReq def initialize(command_id= nil , user_name= nil , user_password= nil , auth_code= nil , token= nil ) @command_id = command_id @user_name = user_name @user_password = user_password @auth_code = auth_code @token = token end def to_json(*a) { "json_class" => self . class , "data" => self .to_json_hash }.to_json(*a) end def to_json_hash { :command_id => @command_id , :user_name => @user_name , :user_password => @user_password , :auth_code => @auth_code , :token => @token } end def self .json_create(json_str) data = json_str[ "data" ] new (data[ "command_id" ], data[ "user_name" ], data[ "user_password" ], data[ "auth_code" ], data[ "token" ]) end attr_accessor :command_id , :user_name , :user_password , :auth_code end class IUserLoginResp def initialize(result= nil , user_name= nil , user_password = nil ) #the login result @result = result #the token holding by client @user_name = user_name @user_password = user_password end def to_json(*a) { "json_class" => self . class , "data" => { :result => @result , :user_name => @user_name , :user_password => @user_password } }.to_json(*a) end def self .json_create(json_str) data = json_str[ "data" ] new (data[ "result" ], data[ "user_name" ], data[ "user_password" ]) end attr_accessor :result , :user_password , :user_name end |
给上面的源代码写测试代码:
|
我们可以看到,测试类继承了Test::Unit::TestCase类,这个类在test/unit库中,test/unit库是Ruby的系统库,成为mini test。
每个测试方法都是以test开头,这点也与JUnit的规则一致,然后assert也是一致,所以如果你熟悉JUnit,那么做Ruby代码的单元测试就不用学习可以直接写。