Junit5 assertThrows Example

Junit and Mockito is something very important for everyone nowadays to avoid the code smells and to deliver the product with high quality.

assertThrows should be used to test when you expect the exception and the specific exception message, here is the example for easy understanding:

import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.assetThrows;
@ExtendWith(MockitoExtension.class)
public class CouponMapperTest {
    @InjectMocks
    private CouponMapperImpl couponMapperImpl;
    
    @Test
    public void testCouponGetWithNullException(){
        Throwable exception = assertThrows(NullPointerException.class, () -> {
           // Given
           CouponDto couponDto = CouponDto.builder().name("50% off").code(null).build();
           
           // when
           Coupon coupon = couponMapperImpl.couponDtoToCoupon(couponDto);
            
        });
        assertEquals("coupon code can not be null", exception.getMessage());
    }
}

Add what exception you want to handle and include all the code within that assertThrows function and validate the exception message outside of that.

4 comments

  • Gave 789win01bet a try. The layout is pretty standard and easy to navigate. The bonuses are tempting, I might sign up and give them a go. So, what do you waiting for? Give it a shot and here is the link: 789win01bet!

  • The jl18app? Yeah, got it on my tablet. Streams work well in my experience so far, but they can be a little laggy sometimes based on location. Pretty slick though! jl18app

  • Yo, checked out jl18applogin the other day. Gotta say, the app login process was smooth as butter. No glitches, no fuss. Pretty decent experience overall. Check it out yourself! jl18applogin

  • Hey guys, was browsing g888 and found some interesting stuff. The site design is pretty slick and easy to navigate. Might be worth a look if you’re bored. Definitely giving it a thumbs up. g888

Leave a Reply to 789win01betCancel reply