In the final part of this series you will see how to refactor your tests. Keeping tests clean is important because it will make testing easier to do in the future.
在重构用户名系列的最后一节,我们介绍如何重构测试。保持测试整洁是非常重要的,因为这样会使得将来的测试更加的简单。
上节用过的测试代码:
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
很明显,重复的地方很多。
重构:
class UserTest < Test::Unit::TestCase
fixtures :users
def test_full_name
assert_equal 'John Doe', get_full_name('John', nil, 'Doe'), "nil middle initial"
assert_equal 'John H. Doe', get_full_name('John', 'H', 'Doe'), "H middle initial"
assert_equal 'John Doe', get_full_name('John', '', 'Doe'), "blank middle initial"
end
def get_full_name(first, middle, last)
User.new(:first_name => first, :middile_initial => middle, :last_name => last).full_name
end
end
本文转自 fsjoy1983 51CTO博客,原文链接:http://blog.51cto.com/fsjoy/131607,如需转载请自行联系原作者