`
wiisola
  • 浏览: 87424 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

#012_重构用户名 PART3

阅读更多
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

这是011中的单元测试代码,是不是很复杂冗长,好吧,让我们来重构一下
# user_test.rb
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, :middle_initial => middle, :last_name => last).full_name
end

代码是清晰多了,但有人提出来testing one assertion per test
详见:http://blog.jayfields.com/2007/06/testing-one-assertion-per-test.html

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics