【问题标题】:How can I ensure that a particular exception is thrown in JUnit5?如何确保在 JUnit5 中引发特定异常?
【发布时间】:2018-10-02 15:06:43
【问题描述】:

使用 JUnit4,您可以例如只写:

@Test (expectedException = new UnsupportedOperationException()){...}

这在 JUnit5 中怎么可能?我试过这种方式,但我不确定这是否相等。

@Test
    public void testExpectedException() {
        Assertions.assertThrows(UnsupportedOperationException.class, () -> {
            Integer.parseInt("One");});

【问题讨论】:

  • 你试过了吗?
  • 不,我不能尝试,因为我的项目只有 JUnit5

标签: java testing junit5


【解决方案1】:

是的,它们是等价的。

public class DontCallAddClass {
    public void add() {
        throws UnsupportedOperationException("You are not supposed to call me!");
    }
}

public class DontCallAddClassTest {

    private DontCallAddClass dontCallAdd = new DontCallAddClass();

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

    @Test
    public void add_throwsException() {
       exception.expect(UnsupportedOperationException.class);
       dontCallAdd.add();
    }

    @Test(expected = UnsupportedOperationException.class)
    public void add_throwsException_differentWay() {
        dontCallAdd.add();
    }

    @Test
    public void add_throwsException() {
        Assertions.assertThrows(UnsupportedOperationException.class, dontCallAdd.add());
    }
}

上述三种测试方法是等效的。在 Junit 5 中使用最后一个。这是较新的方法。它还允许您利用 Java 8 lambda。您还可以检查错误消息应该是什么。见下文:

public class DontCallAddClass {
    public void add() {
        throws UnsupportedOperationException("You are not supposed to call me!");
    }
}

public class DontCallAddClassTest {

    private DontCallAddClass dontCallAdd = new DontCallAddClass();

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

    @Test
    public void add_throwsException() {
       exception.expect(UnsupportedOperationException.class);
       exception.expectMessage("You are not supposed to call me!");
       dontCallAdd.add();
    }

    // this one doesn't check for error message :(
    @Test(expected = UnsupportedOperationException.class)
    public void add_throwsException_differentWay() {
        dontCallAdd.add();
    }

    @Test
    public void add_throwsException() {
        Assertions.assertThrows(UnsupportedOperationException.class, dontCallAdd.add(), "You are not supposed to call me!");
    }
}

查看更多信息:JUnit 5: How to assert an exception is thrown?

希望这能解决问题

【讨论】:

    猜你喜欢
    • 2017-08-24
    • 2021-10-28
    • 2020-08-13
    • 1970-01-01
    • 1970-01-01
    • 2018-06-10
    • 1970-01-01
    • 2015-09-26
    • 2017-05-22
    相关资源
    最近更新 更多