I have two functions with different implementations that return the same value, how do I run the same set of test cases for both the functions without violating the DRY principle? for example: I'm implementing recursive and imperative way of implementing factorial of number. I want same set of test cases to run for both the functions. How can I implement without violating DRY?
Asked
Active
Viewed 162 times
1 Answers
0
Your two implementations share a contract that you can express through a set of tests. For example, imagine two functions that double their input:
def double_by_multiplying(value):
return 2 * value
def double_by_adding(value):
return value + value
Using one of the methods suggested in abstract test case using python unittest, we can write a general set of tests for any function that doubles its input, then create subclasses that use each of our two implementations:
from unittest import TestCase
class DoublingContract:
def test_input_gets_doubled(self):
self.assertEqual(self.implementation(1), 2)
class DoubleMultiplicationTests(DoublingContract, TestCase):
def setUp(self):
self.implementation = double_by_multiplying
class DoubleAdditionTests(DoublingContract, TestCase):
def setUp(self):
self.implementation = double_by_adding

jonrsharpe
- 115,751
- 26
- 228
- 437