Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to verify that static method throws an exception using AssertJ?

When I try to test this method

    static void validatePostcode(final String postcode, final String addressLine)
    {
        if(! hasValidPostcode(postcode, addressLine)) {
            throw new InvalidFieldException("Postcode is null or empty ");
        }
    }

using the following test

    @Test
    public void testThrowsAnException()
    {
        assertThatThrownBy(validatePostcode("", "")).isInstanceOf(InvalidFieldException.class);
    }

I get this error message in IntelliJ

assertThatThrownBy (org.assertj.core.api.ThrowableAssert.ThrowingCallable) in Assertions cannot be applied to (void)

 
Same thing with assertThatExceptionOfType.

Is it possible to test that static method actually throws an unchecked exception using AssertJ? What should I change in my test?

like image 572
Cybex Avatar asked Aug 08 '19 07:08

Cybex


2 Answers

As the compilation error demonstrates, that method expects a throwing callable.

@Test
public void testThrowsAnException()
{
    assertThatThrownBy(() -> validatePostcode("", "")).isInstanceOf(InvalidFieldException.class);
}
like image 91
Ben R. Avatar answered Sep 28 '22 09:09

Ben R.


change to this way. you need to pass lambda to test with assertj

assertThatThrownBy(()->validatePostcode("","")).isInstanceOf(InvalidFieldException.class);
like image 32
Prabhakar Vemulapalli Avatar answered Sep 28 '22 10:09

Prabhakar Vemulapalli