本文共 1402 字,大约阅读时间需要 4 分钟。
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}
转载地址:http://vecci.baihongyu.com/