[转]在Eclipse中使用JUnit4进行单元测试(初级篇)

首先,咱们来一个傻瓜式速成教程,不要问为何,Follow Me,先来体验一下单元测试的快感!框架

首先新建一个项目叫JUnit_Test,咱们编写一个Calculator类,这是一个可以简单实现加减乘除、平方、开方的计算器类,而后对这些功能进行单元测试。这个类并非很完美,咱们故意保留了一些Bug用于演示,这些Bug在注释中都有说明。该类代码以下:ide

package andycpp;

public class Calculator {
    private static int result;    //静态变量,用于存储运行结果
    public void add(int n)
    {
        result=result+n;
    }
    
    public void substract(int n)
    {
        result=result-1;        //Bug:正确的应该是result=result-n;
    }
    
    public void multiply(int n)
    {
        //此方法还没有写好
    }
    
    public void divide(int n)
    {
        result=result/n;
    }
    
    public void square(int n)
    {
        result=n*n;
    }
    
    public void squareRoot(int n)
    {
        for(;;);    //Bug:死循环
    }
    
    public void clear()
    {
        result=0;  //将结果清零
    }
    
    public int getResult()
    {
        return result;
    }
}

 

第二步,将JUnit4单元测试包引入这个项目:在该项目上点右键,点“属性”,如图:单元测试

在弹出的属性窗口中,首先在左边选择“Java Build Path”,而后到右上选择“Libraries”标签,以后在最右边点击“Add Library…”按钮,以下图所示测试

而后在新弹出的对话框中选择JUnit4并点击肯定,如上图所示,JUnit4软件包就被包含进咱们这个项目了。ui

 

第三步,生成JUnit测试框架:在EclipsePackage Explorer中用右键点击该类弹出菜单,选择“New - JUnit Test Case”。以下图所示:spa

在弹出的对话框中,进行相应的选择,以下图所示:3d

点击“下一步”后,系统会自动列出你这个类中包含的方法,选择你要进行测试的方法。此例中,咱们仅对“加、减、乘、除”四个方法进行测试。以下图所示:code

以后系统会自动生成一个新类CalculatorTest,里面包含一些空的测试用例。你只须要将这些测试用例稍做修改便可使用。blog

完整的CalculatorTest代码以下:教程

package andycpp;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.internal.runners.TestClassRunner;
import org.junit.runner.RunWith;

@RunWith(TestClassRunner.class)
public class CalculatorTest {

    private static Calculator calculator=new Calculator();

    
    @Before
    public void setUp() throws Exception {
        calculator.clear();
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test(timeout=1000)
    public void testAdd() {
        calculator.add(2);
        calculator.add(3);
        assertEquals(5, calculator.getResult());
    }

    @Test
    public void testSubstract() {
        calculator.add(10);
        calculator.substract(2);
        assertEquals(8,calculator.getResult());
    }

    @Ignore("Multiply() Not yet implemented")  
    @Test
    public void testMultiply() {
        
    }

    @Test(expected =ArithmeticException.class)
    public void testDivide() {
        calculator.add(8);
        calculator.divide(0);
        assertEquals(4,calculator.getResult());
    }
}

 

第四步,运行测试代码:按照上述代码修改完毕后,咱们在CalculatorTest类上点右键,选择“Run As - JUnit Test”来运行咱们的测试,以下图所示:

运行结果以下:

进度条是红颜色表示发现错误,具体的测试结果在进度条上面有表示“共进行了4个测试,其中1个测试被忽略,一个测试失败”.

至此,咱们已经完总体验了在Eclipse中使用JUnit的方法。

相关文章
相关标签/搜索