【问题标题】:JUNIT - Asserting Exceptions [duplicate]JUNIT - 断言异常[重复]
【发布时间】:2023-03-15 16:10:02
【问题描述】:

我正在使用 JUNIT 4。我尝试使用以下代码断言异常,但没有成功。

@Rule
public ExpectedException thrown = ExpectedException.none();
thrown.expect(ApplicationException.class);

但是,当我使用以下注释时,它可以工作并且测试通过了。

@Test(expected=ApplicationException.class)

如果我遗漏了什么,请告诉我。

import org.junit.Rule;
import org.junit.rules.ExpectedException;

public class Test
{

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

    @org.junit.Test
    public void throwsIllegalArgumentExceptionIfIconIsNull()
    {


        exception.expect(IllegalArgumentException.class);
        toTest();
    }

    private void toTest()
    {
        throw new IllegalArgumentException();
    }
}

【问题讨论】:

标签: java junit junit4


【解决方案1】:

使用 Rule 的另一种方法(更简单?)是在调用后您希望发生异常的地方放置一个 fail()。如果你得到异常,测试方法成功(你永远不会失败)。如果您没有收到异常并且到达了 fail() 语句,则测试失败。

【讨论】:

  • 我也在寻找验证异常类型、代码和消息。您建议的方法是否可行?谢谢。
  • 查看链接的重复问题/答案 - 这就是您要查找的内容
【解决方案2】:

以下代码是使用异常规则的最小示例。

public class Test
{

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

    @org.junit.Test
    public void throwsIllegalArgumentExceptionIfIconIsNull()
    {
        exception.expect(IllegalArgumentException.class);
        toTest();
    }

    private void toTest()
    {
        throw new IllegalArgumentException();
    }
}

另请参阅(Wiki entry about rules)

【讨论】:

  • 谢谢!!我放了 exception.expect(IllegalArgumentException.class);下面 toTest() 并立即意识到愚蠢!
猜你喜欢
  • 1970-01-01
  • 2015-01-10
  • 1970-01-01
  • 2017-03-09
  • 2018-08-21
  • 2018-06-07
  • 2010-09-29
  • 2013-02-19
相关资源
最近更新 更多