入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

Ruby 的 Test::Unit

创建时间:2010-02-25 投稿人: 浏览次数:1551

Ruby 使用一种称为Test::Unit (或者test/unit ) 的测试框架来运行应用程序的测试, 她类似于在其他程序语言中见到的xUnit 框架, 并且实现四个主要的概念:

 

== assertion 是评估表达式及测试结果是否与期望值相同的一行程序代码 。

例如 , 你可能assert (声明,断言) 密码长度至少是6个字符, 若此断言不成立则表示测试失败。

 

== test 是一种方法, 其名称以test 开始。 集合了许多相关的assertion, 每个assertion 测试应用程序的一小部分 ,

例如 , test_for_disallowed_passwords 可能包含验证并拒绝不良密码 (像是太短,含空格 或密码为 "password"等等)的assertion

 

== test case (测试案例)类是Test::Unit::TestCase 的子类, 她包含一组被设计用来测试应用程序功能范围的测试方法。 

 

== test suite (测试案例组)是一组测试案例的集合 。 当运行test suite时, 她测试她所包含的每个测试用例, 你将不需要在Rails应用程序中使用她, 因为Rails 会处理所有测试案例的运行工作。

 

E.g.

实例类:

 class BasicNumber
    def initialize ( number )
        @number = number
      end
  
    def add ( x )
        @number + x
      end
  
    def multiply ( x )
        @number * x
      
      end
    
    end

 

测试类:

 

require "test/unit"
require "BasicNumber.rb"

class TestPost < Test::Unit::TestCase
    def test_add
      n = BasicNumber.new(10)
      assert_equal (14,n.add(4),"This test about add is failure!")
    end
   
    def test_multiply
      n = BasicNumber.new(10)
      assert_equal (4,n.multiply(4),"This test about multiply is failure!")
    end
   
  end

 

常用的assertion如下:

 

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}

 

声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。