Saturday, February 1, 2014

Week4: Use of Unittest

    In this week's lab, we used the Python test module  'unittest' to test the methods of the class we wrote. Accustomed to use doctest in the past, I find unittest unfamiliar. Here I will  summarize some basic use of unittest to remind myself in the future.
    To test a module, we should write in a new module and import unittest module and the the module we want to test.  To get start, we should write a subclass of unittest.TestCase or unittest.FuctionTestCase. The method setUp() runs automatically before testing each method. And likewise, the method tearDown() runs automatically after each test of cases. To test a method or a function, we write methods starting with the four lowercase 'test', so that the module would test it by itself. In each test case method, we call one of the method *.assert**(), such as *.assertEqual() to verify an expected result, *.assertTrue() to check a condition and *.assertRaises() to check an exception to raise. In particular, *.assertRaises() is what I find most uncomfortable because it is something I never use. It should be used as *.assertRaises(exception, callable, *args, **kwds). In lab time, we spend a long time to deal with the raises test. At last, we call the main() function of unittest to test all the subclasses of unittest.TestCase.
    The most important thing to test a module is the choice of test cases. Poorly designed cased may not find important bugs in a module, so it will spend more time in the future. The general consideration includes size, dichotomies, boundaries, order, etc.
    I find unittest extremely useful, because unlike doctest, it can contain more test cases. Also in doctest, it has shortcomings such as dealing with newline character '\n', which is what I found in an exercise. But this will not happen in unittest.

Reference: http://docs.python.org/3.1/library/unittest.html

2 comments:

  1. be careful when writing test for a class, need to write out the setUp method to prepare the text fixture. the default implementation does nothing

    ReplyDelete