Search code examples
junitjunit4

Test if an assertion is thrown


How do I test if an assertion is thrown by the method under test using junit? Heres the method I'm testing:

public int f(int i){
    assert i > 0;
    return i;
}

I'm using junit 4.12.


Solution

  • You can test it by providing parameter in @Test annotation:

    @Test(expected = AssertionError.class)
    public void shouldThrowExceptionWhenIncorrectInput() {
        f(-3);
    }
    

    This will check if the AssertException is thrown. However, if you want to ensure that this function wont be run with incorrect parameters, you have to be aware that assertions can be turned off by running java with -da parameters.

    To ensure that exception is thrown I would suggest throwing IllegalArgumentException inside some validation method, and to provide it with proper message. Then you will be sure that this will always throw exception when incorrect parameters are provided.