Skip to content

UnitTestContainsTooManyAsserts with assertThrows #1519

@volodya-lombrozo

Description

@volodya-lombrozo

We have the following test case:

    void throwsCorrectErrorForRhoAttr(final Class<?> cls) {
        MatcherAssert.assertThat(
            "the message in the error is correct",
            Assertions.assertThrows(
                ExAbstract.class,
                () -> new Dataized(
                    new PhWith(
                        (Phi) cls.getDeclaredConstructor().newInstance(),
                        Phi.RHO,
                        new Data.ToPhi(true)
                    )
                ).take(),
                "EOnumber must be a number"
            ).getMessage(),
            Matchers.equalTo("the 'ρ' attribute must be a number")
        );
    }

As you can see, we have two assertion statements: MatcherAssert.assertThat that checks the error message and the second one if Assertions.assertThrows. Since we have two assertions, we get UnitTestContainsTooManyAsserts error. However, we can't just remove any of there checks if we need to check the error message. We can create some utility method that would catch errors and return their messages, but it looks ugly. Thus, I suggest just skipping such cases where we check error messages. Otherwise our code will be cluttered with @SuppressWarnings("PMD.UnitTestContainsTooManyAsserts"). I've already used it more than 9 times in a middle-size project.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions