[Tutor] How to test a class in python?

Alan Gauld alan.gauld at btinternet.com
Mon Mar 2 09:12:53 CET 2015


On 02/03/15 04:41, Danny Yoo wrote:

> In a test case for a class, we have a few more things in hand.
>
>     1.  The class being tested.
>     2.  The parameters we use to create the class instance.
>     3.  The particular method of the class that we're testing.
>     4.  The parameters we're going to pass as inputs to that method.
>     5.  The expected output we want to see if the method is behaving properly.

And if the class has static or class methods you need
to test those too. Although they are much more like
ordinary functions.

> expected result is supposed to be.  It just so happens that classes
> can have a lot more state, and this can contribute to a few extra
> steps to do the test set up.

I was going to pick this up once the discussion got going, but since 
you've raised it now...

Classes/objects maintain state, so the same method called with the
same inputs can return different outputs at different times.
That rarely happens with functions.
So it is important when testing classes that you exercise the
entire state machine. That may require test cases that call
specific combinations of methods in a particular sequence
with particular sets of inputs. This can lead to a very
large set of tests (sometimes known as a state explosion)
and the best way to handle such tests is to data drive them,
but that usually requires much more complex testing code
than you would normally have for functions.

So although the principles of testing functions and classes
are the same the practice can be much more complex.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list