JUnit4 测试示例

1. JUnit4 测试示例

// Calculator.java
public class Calculator{
    public int add(int a, int b){
        return a + b;
    }

    public int minus(int a, int b){
        return a - b;
    }

    public int square(int a, int b){
        return a * b;
    }

    // Bug: 死循环
    public void squareRoot(int a){
        for(; ;)
            ;
    }

    public int multiply(int a, int b){
        return a * b;
    }

    public int divide(int a, int b) throws Exception{
        if(0 == b){
            throw new ArithmeticException("除数不能为零!");
        }
        return a/b;
    }
}


// 单元测试类
public class CalculatorTest{
    private Calculator cal = new Calculator();

    @BeforeClass
    public static void before(){
        System.out.println("类加载之前....");
    }

    @AfterClass
    public static void after(){
        System.out.println("类被销毁之前...");
    }

    // @BeforeClass和@AfterClass都需要被 static 修饰

    @Before
    public void setUp() throws Exception{
        System.out.println("测试方法开始之前...");
    }

    @After
    public void tearDown() throws Exception{
        System.out.println("测试方法结束!");
    }

    @Test
    @Ignore // 忽略测试
    public void testAdd(){
        int result = cal.add(1, 3);
        System.out.println("测试加法++++");
        Assert.assertEquals(4, result);
    }

    @Test
    public void testMinus(){
        int result = cal.minus(5, 2);
        System.out.println("测试减法----");
        Assert.assertEquals(3, result);
    }

    @Test
    public void testMultiply(){
        int result = cal.multiply(4, 2);
        System.out.println("测试乘法****");
        Assert.assertEquals(8, result);
    }

    // 超时测试, 单位毫秒
    @Test(timeout = 1000)
    public void testSquareRoot(){
        System.out.println("测试平方根");
        cal.squareRoot(4);
    }

    // 异常测试
    @Test(expected = ArithmeticException)
    public void testDivide() throws Exception{
        System.out.println("测试除法...");
        cal.divide(4, 0);
    }
}

1.1 参数测试

  • 需求:如果SquareRoot()方法,需要使用不同的参数,测试多次,需要提供多个@Test方法;
  • JUnit4创建不同参数测试只需要五个步骤:

    创建一个不含参数的通用测试;
    创建一个返回Collection类型的static feeder 方法, 并用@Parameters注释加以修饰;
    为在步骤1中定义的通用方法所要求的参数类型创建类成员;
    创建一个持有这些参数类型的构造函数,并把这些参数类型和步骤3中定义的类成员相应地联系起来;
    通过@RunWith注释,指定测试用例和Parameterized类一起运行;

// 测试用例


参考资料:

猜你喜欢

转载自www.cnblogs.com/linkworld/p/9054363.html