Assertj-core: Assert that Runnable does not throw exception.

Created on 1 Mar 2017  路  3Comments  路  Source: assertj/assertj-core

Summary

Create an assertion type that takes a Runnable and validates that the Runnable does not throw an exception.

Current solution

@Test
public void whenZeroDoesNothing() {
    try {
        throwExceptionIfHigherThanZero(0);
    } catch (Exception e) {
        fail("Should not throw exception");
    }
}

@Test
public void whenHigherThanZeroThrowsException() {
    assertThatThrownBy(() -> throwExceptionIfHigherThanZero(1));
}

private void throwExceptionIfHigherThanZero(int i) {
    if(i > 0) {
        throw new RuntimeException();
    }
}

Proposed (naming is not permanent)

I am not sure about the naming of such method, below is just a proposed naming.

@Test
public void doesNothingWhenZero() throws Exception {
    assertThatCallable(() -> throwExceptionIfHigherThanZero(0)).doesNotThrow();
}
new feature

Most helpful comment

901 has just been integrated providing this feature:

// obviously fails:
assertThatCode(() -> { throw new Exception("boom!"); }).doesNotThrowAnyException();

this will be available in the next release

All 3 comments

901 has just been integrated providing this feature:

// obviously fails:
assertThatCode(() -> { throw new Exception("boom!"); }).doesNotThrowAnyException();

this will be available in the next release

I guess I can close this one then.

Yes, thanks for the information.

Was this page helpful?
0 / 5 - 0 ratings