Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Unit Testing in Java What to Test Know Your Bounds

Handling exceptions in JUnit 5

I can't handle exceptions in JUnit 5 Neither by the Expected keyword nor by the Rule annotation

Kjetil Lorentzen
Kjetil Lorentzen
13,360 Points

Hi Mohamed,

I got into the same problem you were experiencing after watching the videos and using JUnit5. After some googling I found that there is a new (and perhaps improved) way of doing unit testing when testing for expected messages from thrown exceptions.

See below for my implementation:

private Throwable thrown;

@Test
    void overstockingNotAllowed() {
        thrown = assertThrows(IllegalArgumentException.class, () -> {
            bin.restock("Fritos", 2600, 100, 50);
        });
        assertEquals("There are only 10 spots left", thrown.getMessage());
    }
'''

4 Answers

@Test
    void overStockingNotAllowed() {

        assertThrows(IllegalArgumentException.class, () ->
                        bin.restock("Mars", 15, 100, 50),
                "There are only 10 spots left");
Daniel Marin
Daniel Marin
8,021 Points

I'm using junit5 as well here's an example for the vending project:

    @Test
    void notEnoughFundsToDeduct() {
        Assertions.assertThrows(NotEnoughFundsException.class, () -> creditor.deduct(10));
    }
Oziel Perez
Oziel Perez
61,321 Points

Per the docs:

@Test
void exceptionTesting() {
    Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
        throw new IllegalArgumentException("a message");
    });
    assertEquals("a message", exception.getMessage());
}

@Rule no longer exists in JUnit 5 and is superseded by @ExtendedWith. However, there is a migration guide which helps continue to use the @Rule annotation, but this is recommended only to those that have large fixtures with multiple rules and don't wish to rewrite all their tests right away.

In JUnit 5, the test should be rewritten like the following

  @Test
  void overstockingNotAllowed() {
    IllegalArgumentException thrown =
        assertThrows(
            IllegalArgumentException.class,
            () -> {
              bin.restock("Fritos", 2600, 100, 50);
            });
    assertTrue(thrown.getMessage().equals("There are only 10 spots left"));
  }