Unit testing - suitable for all development?

Delaney, Timothy C (Timothy) tdelaney at avaya.com
Mon Mar 8 21:52:33 CET 2004


> From: Roy Smith
> 
> and you want to test the constructor.  Think about what could 
> go wrong.  
> Well, the most obvious thing is that you could have some kind 
> of syntax 
> or semantic error in your constructor code, so the first test 

When I write tests, the order is always (for Python):

1. SyntaxError - is the code syntactically correct. This is the trivial case - import the module.

2. NameError - for example, does the name I'm trying to test actually exist?

3. Creation - can I create the thing I'm trying to test?

4. Everything else ;)

I find it's important to follow the following procedure when creating a new module, to get me into the right frame of mind. By doing this, it's much easier for me to always stay at least one test ahead of the code ...

1. Write the simplest test for the module (syntax).

    import unittest

    import Creature

    if __name__ == '__main__'
        unittest.main()

    # Will fail

2. Create the (empty) module file.

3. Write the NameError and creation test (they're usually one and the same).

    import unittest

    import Creature

    class CreatureTest (unittest.TestCase):

        def testCreation(self):
            obj = Creature.Creature()
            # Will fail with name error

    if __name__ == '__main__'
        unittest.main()

4. Write the basic class definition.

5. Run the test again - if __init__ doesn't take other parameters it will fail.

6. Fix any parameter problems with __init__.

7. I'm now in the right frame of mind for writing the tests and coding.

I find that if I don't follow the above procedure, I'll get into the frame of mind of just coding, and forgetting about anything except ad-hoc functional tests. Discipline is a most important thing.

Tim Delaney




More information about the Python-list mailing list