pivovarit / throwing-function

Checked Exceptions-enabled Java 8+ functional interfaces + adapters

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

the tests should use ExpectedException instead of @Test(expected=SomeException.class)

albertlr opened this issue · comments

As this is a library created explicitly for wrapping checked and unchecked exceptions in lambda expressions, I would say that is pretty important to make sure that the exception that you are wrapping is indeed the exception that was originally created, together with it's message, not just the exception type.

Currently the tests are using @Test(expected = WrappedException.class), which will test only if the exception was tested. It's not able to test also the thrown exception message without writing a try-catch block.

    @Test(expected = WrappedException.class)
    public void shouldWrapInRuntimeExWhenUsingUnchecked() throws Exception {
        // given
        final ThrowingBiFunction<Integer, Integer, Integer, Exception> f1 = (i, j) -> { throw new Exception(); };

        // when
        ThrowingBiFunction.unchecked(f1).apply(42, 42);

        // then RuntimeException is thrown
    }

For this situations JUnit has it's ExpectedException rule, that can be used to just exactly do so:

     @Rule
     public ExpectedException thrown= ExpectedException.none();

    @Test
    public void shouldWrapInWrappedEx() throws Exception {
        final Exception cause = new Exception("some message");
        
        thrown.expect(WrappedException.class);
        thrown.expectMessage("some message");
        thrown.expectCause(is(cause));

        // given
        final ThrowingBiFunction<Integer, Integer, Integer, Exception> f1 = (i, j) -> { throw cause; };

        // when
        f1.unchecked().apply(42, 42);

        // then RuntimeException is thrown
        fail("exception expected");
    }

even more, you can also verify the root cause, or expect based on a matcher.

By changing the tests to use ExpectedException instead of @Test(expected = SomeException.class) the tests should be cleaner and will actually test that we indeed are wrapping the exceptions not just throwing a runtime exception that accidentally or not is called WrappedException, thus testing more than before.

Since assertj is already used in this project I'd use it. It's much more feature rich. Few examples here:
https://github.com/joel-costigliola/assertj-examples/blob/master/assertions-examples/src/test/java/org/assertj/examples/ExceptionAssertionsExamples.java
Btw: Junit rules will be replaced with extensions in Junit5, it'll be easier to migrate with assertj approach.