Skip to content

ExpectedException#expect() should take Matcher<? extends Throwable> as its argument #12

@UrsMetz

Description

@UrsMetz

This is a "re-post" of an issue originally opened at Junit: junit-team/junit4#610. As JUnit is going to depreciate and eventually remove ExpectedException I'm re-raising it hear in order to start a discussion whether this change should be made:

Consider the following test:

public class WrongUsageOfExpectedExceptionApi {
    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void wrongUsageOfExpectedExceptionApi() throws Exception {
        thrown.expect(RuntimeException.class);

        // thrown.expectMessage() should be used here
        // because an exception cannot start with a string
        thrown.expect(startsWith("some message"));
        throw new RuntimeException("some message");
    }
}
...

When you have something like this in a test it can be quite hard to figure out why the test fails.
At the moment ExpectedException#expect takes a Matcher<?> as its argument. By changing it to take only arguments of the type Matcher<? extends Throwable> the compiler could spot the mistake in the test given above.
I tried the code changes needed for the suggested change in the API with the current master (92a3f73) and all tests pass.
I understand that these changes break the API and non-generic Matchers won't work with the new signature of the method but is there any other reason not to have ExpectedException#expect only take arguments of the type Matcher<? extends Throwable>?
Apart from the exclusion of non-generic Matchers the only downside I see is that now you have to specify the generic type: That is you have to write for example

ExpectedException#expect(CoreMatchers.<Throwable>not(CoreMatchers.<Throwable>instanceOf(type)));

instead of

ExpectedException#expect(not(instanceOf(type)));

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions