20.13. Testing classes¶
This page depends on the use of the test module, which is introduced in the testing chapter. If you haven’t covered that chapter yet, you will want to delay reading this page until you do.
To test a user-defined class, you will create test cases that check whether instances are created properly, and you will create test cases for each of the methods as functions, by invoking them on particular instances and seeing whether they produce the correct return values and side effects, especially side effects that change data stored in the instance variables. To illustrate, we will use the Point class that was used in the introduction to classes.
To test whether the class constructor (the
__init__) method is working correctly, create an instance and then make
tests to see whether its instance variables are set correctly. Note that this is a side effect test: the constructor
method’s job is to set instance variables, which is a side effect. Its return value doesn’t matter.
A method like
distanceFromOrigin in the
Point class you saw does its work by computing a return value, so it
needs to be tested with a return value test. A method like
move in the
Turtle class does its work by changing the
contents of a mutable object (the point instance has its instance variable changed) so it needs to be tested with a side
Try adding some more tests in the code below, once you understand what’s there.
Check your understanding