-2

With JUnit4 you could e.g. just write:

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

How is this possible in 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");});
stuckii95
  • 11
  • 3

1 Answers1

1

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

Abraham Ciokler
  • 201
  • 1
  • 8