[英]How can I ensure that a particular exception is thrown in JUnit5?
With JUnit4 you could eg just write:使用 JUnit4,你可以只写:
@Test (expectedException = new UnsupportedOperationException()){...}
How is this possible in JUnit5?这在 JUnit5 中怎么可能? I tried this way, but I'm not sure if this is equal.
我试过这种方式,但我不确定这是否相等。
@Test
public void testExpectedException() {
Assertions.assertThrows(UnsupportedOperationException.class, () -> {
Integer.parseInt("One");});
Yes, those are equivalent.是的,这些是等价的。
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());
}
}
The three test methods above are quivalent.以上三种测试方法是等效的。 In Junit 5 use the last one.
在 Junit 5 中使用最后一个。 It's the newer approach.
这是较新的方法。 It also allows you to take advantage of Java 8 lambdas.
它还允许您利用 Java 8 lambdas。 You can also checks for what the error message should be.
您还可以检查错误消息应该是什么。 See below:
见下文:
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!");
}
}
check there for more information: JUnit 5: How to assert an exception is thrown?在那里查看更多信息: JUnit 5:如何断言抛出异常?
Hope this clear it up希望这清除它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.