Thoughts on Unit Testing

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


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.

for(int i=0;i0)
} else {

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:

  1. b->c->d->e->f->g->h->i
  2. b->c->e->f->g->h->i
  3. 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?


Published by

Bobby Corpus

Is an IT Architect.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s