原创作者: hideto   阅读:1085次   评论:0条   更新时间:2011-05-26    
这次我们来重构我们的测试用例。
require File.dirname(__FILE__) + '/../test_helper'   
  
class UserTest < Test::Unit::TestCase   
  fixtures :users   
  
  def test_full_name_without_middle_initial   
    user = User.new(:first_name => 'John', :last_name => 'Doe')   
    assert_equal 'John Doe', user.full_name   
  end   
  
  def test_full_name_with_middle_initial   
    user = User.new(:first_name => 'John', :middle_initial => 'H', :last_name => 'Doe')   
    assert_equal 'John H. Doe', user.full_name   
  end   
  
  def test_full_name_with_blank_middle_initial   
    user = User.new(:first_name => 'John', :middle_initial => '', :last_name => 'Doe')   
    assert_equal 'John Doe', user.full_name   
  end   
end   

看起来太复杂了是吗?重构!
require File.dirname(__FILE__) + '/../test_helper'   
  
class UserTest < Test::Unit::TestCase   
  fixtures :users   
  
  def test_full_name
    assert_equal 'John Doe', full_name('John', nil, 'Doe'), "nil middle initial"
    assert_equal 'John H. Doe', full_name('John', 'H', 'Doe'), "H middle initial"
    assert_equal 'John Doe', full_name('John', '', 'Doe'), "blank middle initial"
  end

  def full_name(first, middle, last)
    User.new(:first_name => first, :middile_initial => middle, :last_name => last).full_name
  end
end

上面的代码将3个测试方法重构为一个,然后在assert语句末尾加上字符串来标识具体测试类型,full_name被提取出来,代码清晰多了。

但有人投出了反对票,不赞成在一个测试方法里有多个assertion,而应该per方法per assertion。
评论 共 0 条 请登录后发表评论

发表评论

您还没有登录,请您登录后再发表评论

文章信息

Global site tag (gtag.js) - Google Analytics