Software Carpentry
Unit Testing


Introduction


JUnit and Its Children


You Can Skip This Lecture If...


The Big Idea


Checking


Example: Checking Addition


Running Sums


Flawed Implementation


Check and Re-check


Is This Cost-Effective?


Eliminating Redundancy


Testing Exceptions


Manual Exception Testing Example


Testing I/O


I/O Testing Example


Stubs and Mock Objects


Test Performance


Choosing Test Cases


Example: Rectangle Overlap


Solution


What Tests To Write First


Summary


Exercises

Exercise 16.1:

Python has another unit testing module called doctest. It searches files for sections of text that look like interactive Python sessions, then re-executes those sections and checks the results. A typical use is shown below.

def ave(values):
    '''Calculate an average value, or 0.0 if 'values' is empty.
    >>> ave([])
    0.0
    >>> ave([3])
    3.0
    >>> ave([15, -1.0])
    7.0
    '''

    sum = 0.0
    for v in values:
        sum += v
    return sum / float(max(1, len(values)))

if __name__ == '__main__':
    import doctest
    doctest.testmod()

Convert a handful of the tests you have written for other questions in this lecture to use doctest. Do you prefer it to unittest? Why or why not? Do you think doctest makes it easier to test small problems? Large ones? Would it be possible to write something similar for C, Java, Fortran, or Mathematica?

Send comments