加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 在JUnit中断言异常

发布时间:2020-12-15 04:48:31 所属栏目:Java 来源:网络整理
导读:参见英文答案 JUnit Exception Testing????????????????????????????????????5个 我需要编写一个JUnit测试用例,它将测试一个传递不同排列的函数,并得到相应的结果. 成功的用例不返回任何内容,而失败的排列会抛出异常(异常类型无关紧要). 例如. testAppleisSw
参见英文答案 > JUnit Exception Testing????????????????????????????????????5个
我需要编写一个JUnit测试用例,它将测试一个传递不同排列的函数,并得到相应的结果.
成功的用例不返回任何内容,而失败的排列会抛出异常(异常类型无关紧要).

例如. testAppleisSweetAndRed(水果,颜色,味道)
测试会调用以下内容 –

testAppleisSweetAndRed(orange,red,sweet)//throws exception
testAppleisSweetAndRed(apple,green,sour)//throws exception
testAppleisSweetAndRed(apple,sweet)//OK

如果调用的行为符合预期,则测试成功.
断言如何捕获前3次调用以确保它们确实引发预期的异常?

解决方法

如果您使用的是JUnit 4或更高版本,则可以按如下方式执行.你可以使用

@Rule
public ExpectedException exceptions = ExpectedException.none();

?这提供了许多可用于改进JUnit测试的功能.如果您看到以下示例,我将在异常上测试3件事.

>抛出的异常类型
>例外消息
>异常的原因

public class MyTest {

    @Rule
    public ExpectedException exceptions = ExpectedException.none();

    ClassUnderTest testClass;

    @Before
    public void setUp() throws Exception {
        testClass = new ClassUnderTest();
    }

    @Test
    public void testAppleisSweetAndRed() throws Exception {

        exceptions.expect(Exception.class);
        exceptions.expectMessage("this is the exception message");
        exceptions.expectCause(Matchers.<Throwable>equalTo(exceptionCause));

        testClass.appleisSweetAndRed(orange,sweet);
    }

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读