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

2

17

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?

Lindahl answered 8/8, 2019 at 7:38 Comment(7)
why would you test it like that? Use an ExpectedException. baeldung.com/junit-assert-exceptionElytron
We use JUnit4 and I know about @Test(expected = RuntimeException.class) but was looking to do the same using AssertJ.Lindahl
@Lindahl don't use @Test(expected = ...). It's basically like wrapping the entire method body in a try/catch, so the test "passes" if anything in the test throws that exception, not just the thing you intend to test. So, especially for unchecked exceptions, your test can appear to pass even when it's not doing what you think it does.Mindi
@Andy Turner, yeah, this is one of the reasons why I want to switch to AssertJ.Lindahl
@Lindahl but JUnit 4.13 adds assertThrows. No need to, ahem, throw the baby out with the bathwater.Mindi
@Andy Turner Thanks, I'll take a look at it. But I guess for consistency it would be better to stick with one library (AssertJ).Lindahl
AssertJ also lets you chain other assertion after isInstanceOf like hasMessage, see assertj.github.io/doc/…Fante
H
25

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

@Test
public void testThrowsAnException()
{
    assertThatThrownBy(() -> validatePostcode("", "")).isInstanceOf(InvalidFieldException.class);
}
Hogwash answered 8/8, 2019 at 7:59 Comment(1)
Thank you, exactly what I was looking for!Lindahl
D
2

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

assertThatThrownBy(()->validatePostcode("","")).isInstanceOf(InvalidFieldException.class);
Disuse answered 8/8, 2019 at 7:57 Comment(1)
Thanks! Sorry, but answer above was first.Lindahl

© 2022 - 2024 — McMap. All rights reserved.