Ruby test unit的几点注意事项

本文深入解析了 Ruby Test Unit 框架中测试方法和断言的使用技巧,强调了每个测试方法应包含至少一个断言的重要性,并通过实例展示了 setup 和 teardown 方法的应用。同时,文章探讨了测试方法动态生成时可能遇到的问题及解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. First, require the Person class itself and the Test::Unit framework:
# test/person_test.rb
require File.join(File.dirname(__FILE_ _), '..', 'app', 'person')
require 'test/unit'

 

2. Next, extend the framework class Test::Unit::TestCase with a class to contain the
actual tests.

这个就限制了其类或者实例方法的来源,只能使用混入。

 

3. Each test should be written as a method of the test class, and each test
method should begin with the prefix test.

 方法命名的要求, 必须是实例方法,却方法名需要以test开头

 

4. Each test should make one or more assertions:
statements about the code which must be true for the code to be correct.

这一点特别容易被忽视,尤其是使用者是非常规使用的

 

def test_no_assert

    run_command

end

 

def run_command

    puts "hello no assert"

end

 

一个test方法 对应一个统计数据中的一个test(4 tests, 12 assertions, 0 failures, 0 errors, 0 skips)

以上这个的确算是一个test方法,最终的case数量也计算了这个方法,但是实际上,run_command是不会被执行的。要解决这个问题,需要加入assert语句。的确不太灵活。

 

 

5. 最后一点,不是非常肯定,打个标记,还需要分析一下ruby test unit的运行原理。

test unit运行的时候,似乎为每个test 方法都新建一个实例。  不是非常确定,因为我此处采用的是动态生成test方法。 这里出现的这个问题,有可能和 “动态生成test”本身有关系。

 

空口无凭,实例为证:

 

require "test/unit"
class TestSetupTeardown < Test::Unit::TestCase
 
  def setup
    super
    puts "setup"
  end
 
  def test_1
    puts "test_1"
  end

  def test_2
    puts "test_2"
  end
 
  def teardown
    super
    puts "teardown"
  end
end

 

各位看官,看输出:

 

[biadmin@svltest358 test]$ ruby ./test_setup_teardown.rb
Loaded suite ./test_setup_teardown
Started
setup
test_1
teardown
.setup
test_2
teardown
.
Finished in 0.000203 seconds.

2 tests, 0 assertions, 0 failures, 0 errors, 0 skips

Test run options: --seed 4017

 

看官们,发表一下你的见解吧!

 

所以需要注意几个地方,

1. 当各个test的之间需要共享信息,比如保存log到一个文件时,就得注意,看使用w还是a

2. 考虑变量和常量,以及实例变量,类变量的区别和在此处的作用了。

3. 对应setup和teardown,这两个方法共享的代码块,是过程,而不是结果。 尤其是对应setup,比如通过setup获取了某个值,并不所有的test方法都公用这个值(普通的值),而是所有的代码块都运行一次setup,重新获取该值。这是初学者经常出现误解的地方。


老外st上吹了半天的神奇的Bitcoin,看起来似乎也没什么难度呀,无非就是Digital signatures and  peer-to-peer ,论文看了半天,sb日本人英语也是差....

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值