unittest 测试用例中的重复代码 [英] Repetitive code in unittest testcase
问题描述
我有一个看起来像这样的测试用例:
I have a testcase that looks like this:
def MyTestCase(unittest.Testcase):
def test_input01(self):
input = read_from_disk('input01')
output = run(input)
validated_output = read_from_disk('output01')
self.assertEquals(output, validated_output)
def test_input02(self):
input = read_from_disk('input02')
# ...
# and so on, for 30 inputs, from input01 to input30
现在,我明白测试代码可能有点重复,因为简单比简洁更重要.但这变得非常容易出错,因为当我决定更改此处使用的某些函数的签名时,我不得不在所有 30 个地方进行更改.
Now, I understand that test code can be a bit repetitive, since simplicity is more important than conciseness. But this is becoming really error-prone, since when I decided to change the signature of some functions used here, I had to make the change in all 30 places.
我可以将其重构为对已知输入的循环,但我确实希望每个输入保持一个单独的测试,所以我认为我应该制作 test_inputxx
方法.
I could refactor this into a loop over the known inputs, but I do want each input to remain a separate test, so I thought I should be making the test_inputxx
methods.
我做错了什么?
推荐答案
编写一个辅助函数来去除测试用例中的重复:
Write a helper function to remove the repetition from the test cases:
def MyTestCase(unittest.Testcase):
def run_input_output(self, suffix):
input = read_from_disk('input'+suffix)
output = run(input)
validated_output = read_from_disk('output'+suffix)
self.assertEquals(output, validated_output)
def test_input01(self): self.run_input_output('01')
def test_input02(self): self.run_input_output('02')
def test_input03(self): self.run_input_output('03')
这篇关于unittest 测试用例中的重复代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!