廖雪峰Java8JUnit单元测试-2使用JUnit-2异常测试

1.异常测试

对可能抛出的异常进行测试:

  • 异常本身是方法签名的一部分:
    * public static int parseInt(String s) throws NumberFormatException
  • 测试错误的输入是否导致特定的异常:
    * Integer.parseInt(null)
    * Integer.parseInt("")
    * Integer.parseInt("xyz")

2.异常测试的方法:

  • 使用try..catch (Exception e)捕获异常,但这样会编写许多try..catch代码
  • expected测试异常,推荐

    2.1示例1

package com.testList;

import org.junit.*;

import static org.junit.Assert.fail;

public class SequenceTest {
    //使用try...catch
    @Test
    public void test1() throws Exception{
        try {
            Integer.parseInt(null);
            fail("should throw java.lang.NumberFormatException");
        }catch (NumberFormatException e){
            System.out.println("pass");
        }
    }
    //使用expected捕获异常
    @Test(expected = NumberFormatException.class)
    public void test2() throws Exception{
        Integer.parseInt("p");
    }
}

1418970-20190417113835693-1886475730.png

2.2示例2

Calculator.java

package com.testList;

public class Calculator {
    public int calculator(String expression){
        if (expression == null){
            throw new NumberFormatException();
        }
        String[] ss = expression.split("\\+");
        int sum = 0;
        for(String s:ss){
            sum = sum + Integer.parseInt(s.trim());
        }
        return sum;
    }
}

CalculatorTest.java

package com.testList;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.Calendar;

import static org.junit.Assert.*;

public class CalculatorTest {
    Calculator calc;
    @Before
    public void setUp(){
        calc = new Calculator();
    }
    @Test(expected = NumberFormatException.class)
    public void testCalcWithEmptyString(){
        int r = calc.calculator("");
    }
    @Test(expected =NumberFormatException.class)
    public void testCalcAdd3Numbers(){
        int r = calc.calculator(null);
    }
    @After
    public void tearDown(){
        calc = null;
    }
}

1418970-20190417114448977-2021492915.png

3.总结

  • 测试异常可以使用@Test(expected = Exception.class)
  • 对可能发生的每种类型的异常进行测试

转载于:https://www.cnblogs.com/csj2018/p/10721839.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值