如果您编写类似
的测试类class MyTest < Test::Unit::TestCase
def setup
end
def test_1
flunk
end
def test_1
assert true
end
end
忽略第一个test_1。虽然它看起来像一个愚蠢的错误,但它可能发生在复制和粘贴编程中。除了运行
grep test test_me.rb | wc
并将其与测试单元所说的运行,或使用rcov或heckle或使用-w运行的测试数量进行比较,您如何检测此类问题?
另外,有没有办法指定不应该覆盖测试方法?
编辑:正在测试的方法有一个参数,其中包含6个左右的可能值,测试人员希望测试每个方案。这就是使用复制和粘贴编程的原因。我可以设想的唯一替代方案是一个六元素的参数和期望值数组。
答案 0 :(得分:5)
您可以利用Ruby的method_added
,只要将方法添加到类中,就会调用它。您应该可以将某些内容添加到您包含的模块中,但这是在测试类中执行此操作的简单示例。
class MyTest < Test::Unit::TestCase
@@my_tests = []
def self.method_added(sym)
raise "#{sym} already defined!" if @@my_tests.include? sym
@my_tests << sym
end
def test_foo_1
end
def test_foo_2
end
def test_foo_1
end
end
答案 1 :(得分:2)
编辑:正在测试的方法有一个 参数有6左右可能 值,测试人员想测试 每个场景。这就是为什么复制和 使用了粘贴编程。
在这种情况下,我这样做:
def test_foo
test_cases = [
{:param => 1, :expected => 'whatever is expected'},
{:param => 2, :expected => 'whatever is expected'},
{:param => 3, :expected => 'whatever is expected'},
{:param => 4, :expected => 'whatever is expected'},
{:param => 5, :expected => 'whatever is expected'},
{:param => 6, :expected => 'whatever is expected'}
]
for test_case in test_cases
do_the_test(test_case)
end
end
def do_the_test(test_case)
# test code here
end
这完全避免了复制和粘贴,如上所述,这是不好的
唯一的 替代方案我可以设想这样一个 场景是一个六元素阵列 参数和期望值。
完全!
答案 2 :(得分:2)
关于HermanD的答案,因为这是Ruby!,你也可以直接在课堂上这样做来创建独特的测试方法:
class MyObjectTest < Test::Unit::TestCase
[
{:param => 1, :expected => 'whatever is expected'},
{:param => 2, :expected => 'whatever is expected'},
{:param => 3, :expected => 'whatever is expected'},
{:param => 4, :expected => 'whatever is expected'},
{:param => 5, :expected => 'whatever is expected'},
{:param => 6, :expected => 'whatever is expected'}
].each do |test_case|
define_method :"test_using_#{test_case[:param]}_should_return_#{params[:expected].underscore}" do
assert_equal test_case[:expected], MyObject.new.do_something_with(test_case[:param])
end
end
end
使用Rspec(或Shoulda)的句子(如语言)感觉更自然:
describe MyObject do
[
{:param => 1, :expected => 'whatever is expected'},
{:param => 2, :expected => 'whatever is expected'},
{:param => 3, :expected => 'whatever is expected'},
{:param => 4, :expected => 'whatever is expected'},
{:param => 5, :expected => 'whatever is expected'},
{:param => 6, :expected => 'whatever is expected'}
].each do |test_case|
it "should return #{test_case[:expected]} when using #{test_case[:param]}" do
MyObject.new.do_something_with(test_case[:param]).should == test_case[:expected]
end
end
end
答案 3 :(得分:1)
如果你给你的测试提供正确的描述性名称,这真的是一个问题吗?以下是我最近项目中一些测试方法名称的示例:
test_should_not_do_html_escaping_for_administrators
test_should_not_be_able_to_create_project_with_company_user_doesnt_own
test_should_be_able_to_edit_own_projects
test_should_not_be_able_to_edit_others_projects
如果您的测试名称足够短,以至于您可以轻松覆盖或复制它们,那么您可能无法描述每个实际测试的内容。
答案 4 :(得分:0)
避免复制粘贴编程。如果必须,重新绑定关键快捷键。
答案 5 :(得分:0)
测试单元的gem版本能够检测2.0.7的测试重新定义。