Site icon NgDeveloper

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.

Exit mobile version