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. It's the newer approach. It also allows you to take advantage of 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?
Hope this clear it up