The java community is very fortunate to have a standard unit testing tool in JUnit. In order to demonstrate how to use the tool, the JUnit documentation illustrated it using simple examples. Now that we know how to use the tool, it now remains for us to use it effectively.

Perhaps the first thing we need to know is how do we make sure we have tested the possible scenarios of our code. In order to answer this question, we need to know the control flow of our code. In basic programming, we know that controls flows are of the form

if(statement){ doSomething(); } while(condition){ doSomething(); } for(...){ doSomething(); }

We can visualize these control structures using a graph. The `if`

structure can be drawn like the figure below:

The `if`

block is shown in the colored box. The node labeled 1 is a statement before the `if`

block and the node labeled 4 is the statement after the `if`

block. The two arrows from node 2 to node 3 represent the two possibilities, namely `true`

and `false`

.

The `do`

and `for`

have a similar representation. We can convert a `for`

statement to a `do`

statement. This is how to convert a `do`

or `for`

The `do ... while`

graph is different. The loop will have to be entered first before a check is made for the loop to terminate. Here is how the `do ... while`

graph looks like:

The next thing we want to do is to illustrate these graphical flow construction. Here is an algorithm i took from a book.

if(values.length>1){ for(int i=0;i0) sum+=values[i]; } } else { sum=values[0]; }

The flow graph of this code is shown below:

The `for`

loop is highlighted. With a digram like this, it would be easy for us the determine the paths we want to exercise in our unit testing.

The possible paths of this flow graph are:

`b->c->d->e->f->g->h->i`

`b->c->e->f->g->h->i`

`a->i`

To test the first flow, assuming that the path `d`

is the false part of the `if`

statement, a vector `values`

whose length is greater than 1 with all entries negative.

For the second path, we need a vector with more than 1 entry and all entries positive. To test the third path, we need a vector of length 1. What would happen if the length of the vector is zero?