Ruby中也提供了单元测试的框架,类似Java中的JUnit,此框架在Ruby中被成为mini test。

  我们先看一个例子,这个是我的源代码:


require'json'
modulePMU_INTERFACE
    classIUserLoginReq
        definitialize(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
 
        defto_json(*a)
            {
                "json_class"=>self.class,
                "data"=>self.to_json_hash
            }.to_json(*a)
        end
 
        defto_json_hash
            {:command_id=>@command_id,:user_name=>@user_name,:user_password=>@user_password,:auth_code=>@auth_code,:token=>@token}
        end
 
        defself.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
 
    classIUserLoginResp
        definitialize(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
 
        defto_json(*a)
            {
                "json_class"=>self.class,
                "data"=> {:result=>@result,:user_name=>@user_name,:user_password=>@user_password}
            }.to_json(*a)
        end
 
        defself.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


  给上面的源代码写测试代码:


require'test/unit'
require'json'
 
require_relative'../../../source/server/service/pmu_interface/app_interface'
classTestInterface < Test::Unit::TestCase
    deftest_user_login_req
        req =PMU_INTERFACE::IUserLoginReq.new(1,'a@b.com','aa','1234','')
        str = req.to_json
        req2 =JSON.parse(str)
        assert(str !=nil&& req2.command_id == req.command_id)
    end
 
    deftest_user_login_resp
        req =PMU_INTERFACE::IUserLoginResp.new(1,'1234','1234') 
        str = req.to_json
        req2 =JSON.parse(str)
        assert(str !=nil&& req2.result == req.result)
    end
end
 


  我们可以看到,测试类继承了Test::Unit::TestCase类,这个类在test/unit库中,test/unit库是Ruby的系统库,成为mini test。

  每个测试方法都是以test开头,这点也与JUnit的规则一致,然后assert也是一致,所以如果你熟悉JUnit,那么做Ruby代码的单元测试不用学习可以直接写。