« 11. Design Principle #3 - Don't Repeat Yourself (DRY) | Main | 9. Design Principle #1 - Dumb Test »
November 29, 2004
10. Design Principle #2 - Independent Test
Each test leaves the application in the same pre-defined state, irrespective of whether the test passed or failed.
In order to ensure test integrity, it is important that tests be unaffected by the outcome of other tests. Each test expects to start from a constant application state. This requires each test to de-initialize to this constant state upon completion or failure. If this does not occur then subsequent tests will fail to execute. Unit testing frameworks such as JUnit recognize the importance of this principle and have mechanisms to initialize and de-initialize each test in order to keep the application in a consistent state (i.e. using setUp() and tearDown() methods).
For our sample application, it is important that each test start on the login page, with an empty shopping cart. This necessitates a mechanism for emptying the shopping cart and logging out at the end of each test or upon test failure. If we use the Template pattern, we can insert these common steps of initialization and de-initialization, right into the Template, thereby relieving test writers from having to remember to include these steps in every test and ensuring tests stay independent.
Figure 10: Common initialization and de-initialization steps for each test case.
protected void setUp() {
login(); // <------ common setup code for all test cases
searchForItem1();
cartAction1();
searchForItem2();
cartAction2();
emptyCart(); // <------- common tear down code for all test cases
logout();
}
Posted by Misha Rybalov at November 29, 2004 08:21 PM