Video in progress
How do you check in JUnit 5 that a method throws an exception in the right situation?
Use assertThrows(ExceptionType.class, () -> ...). It fails the test if the code in the lambda doesn't throw an exception of that type, and it returns the thrown exception, so you can check its message too.
📖 Answer
@Test
void manfiy_summa_qabul_qilinmaydi() {
var service = new TransferService();
var ex = assertThrows(IllegalArgumentException.class,
() -> service.transfer("A", "B", new BigDecimal("-100")));
assertEquals("summa musbat bo'lishi kerak", ex.getMessage());
}
A few nuances:
assertThrowsalso accepts a subclass. If you writeRuntimeException.class, anIllegalArgumentExceptionpasses too. If you need the exact type, useassertThrowsExactly(JUnit 5.8+).- Put only the one call that's expected to throw inside the lambda. If you put setup code in there, the test can pass even when the exception comes from the wrong place.
- For the opposite case there's
assertDoesNotThrow(() -> ...).
The @Test(expected = ...) approach from JUnit 4 doesn't exist in JUnit 5. It was dangerous for exactly this reason: it covered the whole method.
Sign up to mark studied questions and save your progress.