JUnit继续在预期的异常之后断言 [英] JUnit continue to assert things after expected exception

查看:385
本文介绍了JUnit继续在预期的异常之后断言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些类似

@Test(expected = IllegalArgumentException.class)
public void cdIntoNonExistantFolder() {
    cdTool.changeDirectory("nonexistant");
    assertThat(cdTool.getStatusCode(), not(equalTo(0)));
}

我相信 assertThat 不运行为 changeDirectory 将抛出异常。有可能使它仍然运行吗?

I believe the assertThat does not run as changeDirectory will throw the exception. Is it possible to make it still run?

推荐答案

我宁愿在单元测试中避免任何try / catch结构。以下是 Catch-Exception 的一种可能性:

I'd rather avoid any try/catch structures in unit-tests. Here's one possibility with Catch-Exception:

@Test
public void cdIntoNonExistantFolder() {
    catchException(cdTool).changeDirectory("nonexistant");

    assertThat(caughtException(), instanceOf(IllegalArgumentException.class));
    assertThat(cdTool.getStatusCode(), not(equalTo(0)));
}

或JUnit 5:

@Test
public void cdIntoNonExistantFolder() {
    expectThrows(IllegalArgumentException.class, () -> {
        cdTool.changeDirectory("nonexistant");
    });

    assertThat(cdTool.getStatusCode(), not(equalTo(0)));
}

这篇关于JUnit继续在预期的异常之后断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆