开发者

unit testing with junit4

how do i creat开发者_如何学JAVAe a test suite in junit4 ??


Here is one example:

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

}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜