Skip to content

Using DDT with Unit Tests

Grant Winney edited this page Sep 23, 2016 · 7 revisions

One way to keep your unit tests DRY is to run multiple values through the same single unit test. In some libraries, like NUnit (C#), this is referred to as a TestCase.

For example, using NUnit again, it reduces code like this...

public void DivideTest_DividingTwelveByThreeIsFour()
{
  Assert.AreEqual(4, 12 / 3);
}
public void DivideTest_DividingTwelveByTwoIsSix()
{
  Assert.AreEqual(6, 12 / 2);
}
public void DivideTest_DividingTwelveByFourIsThree()
{
  Assert.AreEqual(3, 12 / 4);
}

... to something like this:

[TestCase(12,3,4)]
[TestCase(12,2,6)]
[TestCase(12,4,3)]
public void DivideTest(int n, int d, int q)
{
  Assert.AreEqual(q, n / d);
}

Similar behavior can be achieved in Python with a library called Data-Driven Tests (DDT). There is documentation available, including example usages.

Here's one of the tests I wrote:

@ddt
class JoystickColorWheelTests(unittest.TestCase):

    @data((510, 484, False),
          (510.1, 484.1, True))
    @unpack
    def test_is_joystick_near_center(self, x, y, expected_result):
        self.assertEqual(jcw.is_joystick_near_center(x, y), expected_result)

One of the caveats is that, due to whatever is happening under the covers, running a single test in PyCharm kicks out this error:

Traceback (most recent call last):
  File "/Applications/PyCharm CE.app/Contents/helpers/pycharm/utrunner.py", line 156, in <module>
    testLoader.makeTest(getattr(testCaseClass, a[2]), testCaseClass))
AttributeError: 'TestLoader' object has no attribute 'makeTest'

Process finished with exit code 1

There's probably a work-around out there, but for now running the entire suite of tests instead of a single one fixes the issue.

Clone this wiki locally