[Ruby]单元测试

Rabia ·
更新时间:2024-09-20
· 569 次阅读

  1. Test::Unit框架

  Test::Unit框架基本上是将3个功能包装到一个整洁的包中:

  1) 它提供了一种表示单个测试的方式。

  2) 它提供了一个框架来组织测试。

  3) 它提供了灵活的方式来调用测试。

  Test::Unit提供一系列断言来达到与if语句相同的目标,虽然存在许多不同风格的断言,但是它们基本上都遵循相同的模式,例如:

require 'test/unit' Class TestBug < Test::Unit::TestCase def test_simple assert_equal('ok', MyClass.new(1).to_s) assert_equal('error', MyClass.new(2).to_s) end end

  还可以测试是否引发异常,例如:

require 'test/unit' Class TestBug < Test::Unit::TestCase def test_raise assert_raise(RuntimeError) {MyClass.new('null')} assert_nothing_raised() {MyClass.new('normal')} end end

  2. 组织测试

  单元测试,可以被组织成更高层的形式,叫做测试用例,或分解成较底层的形式,也是测试方法。测试用例通常包括和某个特定功能或特性相关的所有测试。

  表示测试的类必须是Test::Unit::TestCase的子类。含有断言的方法名必须以test开头。Test::Unit使用反射来查找要运行的测试,而只有以test开头的方法才符合条件。

  可以把通用的一些代码提取到setup和teardown方法中。在一个TestCase类中,一个叫做setup的方法将在每个测试方法之前运行,而叫做teardown的方法在每个测试方法结束之后运行,例如:

require 'test/unit' require 'dbi' Class TestDB < Test::Unit::TestCase def setup @db = DBI.connetct('DBI:mysql:playlists') end def test_count assert_equal('10', MyClass.new(1).get_count) end def teardown @db.disconnect end end



单元 单元测试 Ruby 测试

需要 登录 后方可回复, 如果你还没有账号请 注册新账号
相关文章
Lassie 2021-02-21
729