Skip to content

Prefer @Test(expected=Exception.class) as opposed to explicit try-catch #761

@greg-at-moderne

Description

@greg-at-moderne

What problem are you trying to solve?

Code readability by using JUnit built-in features.

When using JUnit (and possibly other test frameworks too) one can use expected=... argument to the @Test annotation. Instead of manually handling the failure/success expectations in the test code with try catch.

What precondition(s) should be checked before applying this recipe?

No other checks being done, incl. no checks for the specific content of the Exception objects, etc.

Describe the situation before applying the recipe

    @Test
    public void test() {
        try {
            // ... some code here
            fail("should have thrown an exception");
        } catch (Exception e) {
            // expected
        }
    }

Describe the situation after applying the recipe

    @Test(expected = Exception.class)
    public void test() {
        // ... some code here
    }

OSS repro

Example:

Metadata

Metadata

Assignees

No one assigned

    Labels

    recipeRecipe request

    Type

    No type
    No fields configured for issues without a type.

    Projects

    Status
    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions