unit-testing Unit testing of Loops (Java) Single loop test

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

These are loops in which their loop body contains no other loops (the innermost loop in case of nested).

In order to have loop coverage, testers should exercise the tests given below.

Test 1 :Design a test in which loop body shouldn’t execute at all (i.e. zero iterations)

Test 2 :Design a test in which loop–control variable be negative (Negative number of iterations)

Test 3 :Design a test in which loop iterates only once

Test 4 :Design a test in which loop iterates twice

Test 5 :Design a test in which loop iterates certain number of times , say m where m < maximum number of iterations possible

Test 6 :Design a test in which loop iterates one less than the maximum number of iterations

Test 7 :Design a test in which loop iterates the maximum number of iterations

Test 8 :Design a test in which loop iterates one more than the maximum number of iterations

Consider the below code example which applies all the conditions specified.

public class SimpleLoopTest {

private int[] numbers = {5,-77,8,-11,4,1,-20,6,2,10};

/** Compute total of  positive numbers in the array 
 *  @param numItems number of items to total.
 */
public int findSum(int numItems)
{
    int total = 0;
    if (numItems <= 10) 
    {
        for (int count=0; count < numItems; count = count + 1)
        {
          if (numbers[count] > 0)
             {
                total = total + numbers[count];
             }
        }                
    }
    return total;
}

}

public class TestPass extends TestCase {

public void testname() throws Exception {
    
    SimpleLoopTest s = new SimpleLoopTest();        
    assertEquals(0, s.findSum(0));    //Test 1
    assertEquals(0, s.findSum(-1));   //Test 2
    assertEquals(5, s.findSum(1));    //Test 3
    assertEquals(5, s.findSum(2));    //Test 4
    assertEquals(17, s.findSum(5));   //Test 5
    assertEquals(26, s.findSum(9));   //Test 6
    assertEquals(36, s.findSum(10));  //Test 7
    assertEquals(0, s.findSum(11));   //Test 8
}

}



Got any unit-testing Question?