使用JUnit4,您可以例如只需写:
@Test (expectedException = new UnsupportedOperationException()){...}
在JUnit5中怎么可能?我尝试过这种方式,但不确定是否相等。
@Test
public void testExpectedException() {
Assertions.assertThrows(UnsupportedOperationException.class, () -> {
Integer.parseInt("One");});
答案 0 :(得分: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?
希望这可以清除