views:

88

answers:

2

how do i create a test suite in junit4 ??

+6  A: 

Here is one example:

@RunWith(Suite.class)
@Suite.SuiteClasses(
        {
            TestClass1.class,
            TestClass2.class,
        })
public class DummyTestSuite
{

}
Uri
+1  A: 

Unit Testing is really easy and best explained on a simple example.

We'll have the following class calculating the average of an array:

package com.stackoverflow.junit;

public class Average {
    public static double avg(double[] avg) {
        double sum = 0;

        // sum all values
        for(double num : avg) {
            sum += num;
        }


        return sum / avg.length;
    }
}

Our JUnit test will now test some basic operations of this method:

package com.stackoverflow.junit;

import junit.framework.TestCase;

public class AverageTest extends TestCase {
    public void testOneValueAverage() {
        // we expect the average of one element (with value 5) to be 5, the 0.01 is a delta because of imprecise floating-point operations
        double avg1 = Average.avg(new double[]{5});
        assertEquals(5, avg1, 0.01);

        double avg2 = Average.avg(new double[]{3});
        assertEquals(3, avg2, 0.01);        
    }

    public void testTwoValueAverage() {
        double avg1 = Average.avg(new double[]{5, 3});
        assertEquals(4, avg1, 0.01);

        double avg2 = Average.avg(new double[]{7, 2});
        assertEquals(4.5, avg2, 0.01);      
    }

    public void testZeroValueAverage() {
        double avg = Average.avg(new double[]{});
        assertEquals(0, avg, 0.01);
    }
}

The first two test cases will show that we implemented the method correct, but the last test case will fail. But why? The length of the array is zero and we are diving by zero. A floating point number divided by zero is not a number (NaN), not zero.

Tobias P.
You should have continued reading the question after the title ;-)
Joachim Sauer
i have read your post ;)But at the beginning a short self-compiling example is worth more than some basic explaniton or class "wrapper" showing how to define a test suite but not any test case
Tobias P.
It's not my post, the question is about a **test suite** (i.e. a grouping of test cases) and about JUnit 4 (your example shows a JUnit 3-style test).
Joachim Sauer
oh, your're right.he has written test case in the title and therefore i have read test case in his "description" again, my fault.
Tobias P.