diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 38427ceb5afe..5ad8e0771984 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -45,7 +45,7 @@ jobs: with: persist-credentials: false - name: Initialize CodeQL - uses: github/codeql-action/init@3599b3baa15b485a2e49ef411a7a4bb2452e7f93 # v3.30.5 + uses: github/codeql-action/init@64d10c13136e1c5bce3e5fbde8d4906eeaafc885 # v3.30.6 with: languages: ${{ matrix.language }} build-mode: ${{ matrix.build-mode }} @@ -60,6 +60,6 @@ jobs: -Dscan.tag.CodeQL \ classes - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@3599b3baa15b485a2e49ef411a7a4bb2452e7f93 # v3.30.5 + uses: github/codeql-action/analyze@64d10c13136e1c5bce3e5fbde8d4906eeaafc885 # v3.30.6 with: category: "/language:${{matrix.language}}" diff --git a/.github/workflows/ossf-scorecard.yml b/.github/workflows/ossf-scorecard.yml index 92b42ea17829..867274ab9601 100644 --- a/.github/workflows/ossf-scorecard.yml +++ b/.github/workflows/ossf-scorecard.yml @@ -57,6 +57,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard (optional). # Commenting out will disable upload of results to your repo's Code Scanning dashboard - name: "Upload to code-scanning" - uses: github/codeql-action/upload-sarif@3599b3baa15b485a2e49ef411a7a4bb2452e7f93 # v3.30.5 + uses: github/codeql-action/upload-sarif@64d10c13136e1c5bce3e5fbde8d4906eeaafc885 # v3.30.6 with: sarif_file: results.sarif diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index f265ee366e3a..58974e90b9a9 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -91,7 +91,7 @@ asciidoctorPdf = { id = "org.asciidoctor.jvm.pdf", version.ref = "asciidoctor-pl bnd = { id = "biz.aQute.bnd", version.ref = "bnd" } buildParameters = { id = "org.gradlex.build-parameters", version = "1.4.4" } commonCustomUserData = { id = "com.gradle.common-custom-user-data-gradle-plugin", version = "2.4.0" } -develocity = { id = "com.gradle.develocity", version = "4.2" } +develocity = { id = "com.gradle.develocity", version = "4.2.1" } download = { id = "de.undercouch.download", version = "5.6.0" } errorProne = { id = "net.ltgt.errorprone", version = "4.3.0" } foojayResolver = { id = "org.gradle.toolchains.foojay-resolver", version = "1.0.0" } diff --git a/junit-platform-commons/src/testFixtures/java/org/junit/platform/commons/test/PreconditionAssertions.java b/junit-platform-commons/src/testFixtures/java/org/junit/platform/commons/test/PreconditionAssertions.java index 926ff63204e3..b8cc0bd19998 100644 --- a/junit-platform-commons/src/testFixtures/java/org/junit/platform/commons/test/PreconditionAssertions.java +++ b/junit-platform-commons/src/testFixtures/java/org/junit/platform/commons/test/PreconditionAssertions.java @@ -32,10 +32,22 @@ public static void assertPreconditionViolationNotNullFor(String name, ThrowingCa assertPreconditionViolationFor(throwingCallable).withMessage("%s must not be null", name); } + public static void assertPreconditionViolationNotBlankFor(String name, ThrowingCallable throwingCallable) { + assertPreconditionViolationFor(throwingCallable).withMessageContaining("%s must not be blank", name); + } + + public static void assertPreconditionViolationNotEmptyFor(String name, ThrowingCallable throwingCallable) { + assertPreconditionViolationFor(throwingCallable).withMessage("%s must not be empty", name); + } + public static void assertPreconditionViolationNotNullOrBlankFor(String name, ThrowingCallable throwingCallable) { assertPreconditionViolationFor(throwingCallable).withMessage("%s must not be null or blank", name); } + public static void assertPreconditionViolationNotNullOrEmptyFor(String name, ThrowingCallable throwingCallable) { + assertPreconditionViolationFor(throwingCallable).withMessage("%s must not be null or empty", name); + } + public static ThrowableAssertAlternative assertPreconditionViolationFor( ThrowingCallable throwingCallable) { diff --git a/junit-vintage-engine/src/test/java/org/junit/vintage/engine/descriptor/OrFilterTests.java b/junit-vintage-engine/src/test/java/org/junit/vintage/engine/descriptor/OrFilterTests.java index 6e5d29569b23..470fe5a525e7 100644 --- a/junit-vintage-engine/src/test/java/org/junit/vintage/engine/descriptor/OrFilterTests.java +++ b/junit-vintage-engine/src/test/java/org/junit/vintage/engine/descriptor/OrFilterTests.java @@ -11,8 +11,8 @@ package org.junit.vintage.engine.descriptor; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotEmptyFor; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.mock; @@ -23,7 +23,6 @@ import java.util.Set; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.runner.Description; import org.junit.runner.manipulation.Filter; @@ -34,8 +33,7 @@ class OrFilterTests { @Test void exceptionWithoutAnyFilters() { - var actual = assertThrows(PreconditionViolationException.class, () -> new OrFilter(Set.of())); - assertEquals("filters must not be empty", actual.getMessage()); + assertPreconditionViolationNotEmptyFor("filters", () -> new OrFilter(Set.of())); } @Test diff --git a/jupiter-tests/src/test/java/org/junit/jupiter/api/AssertAllAssertionsTests.java b/jupiter-tests/src/test/java/org/junit/jupiter/api/AssertAllAssertionsTests.java index 0bee5bb609be..0c11dd9083c4 100644 --- a/jupiter-tests/src/test/java/org/junit/jupiter/api/AssertAllAssertionsTests.java +++ b/jupiter-tests/src/test/java/org/junit/jupiter/api/AssertAllAssertionsTests.java @@ -12,13 +12,14 @@ import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.AssertionTestUtils.assertMessageEquals; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotNullFor; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotNullOrEmptyFor; import java.io.IOException; import java.util.Collection; @@ -26,7 +27,6 @@ import java.util.stream.Stream; import org.junit.jupiter.api.function.Executable; -import org.junit.platform.commons.PreconditionViolationException; import org.opentest4j.AssertionFailedError; import org.opentest4j.MultipleFailuresError; @@ -40,36 +40,36 @@ class AssertAllAssertionsTests { @SuppressWarnings("DataFlowIssue") @Test void assertAllWithNullExecutableArray() { - assertPrecondition("executables array must not be null or empty", () -> assertAll((Executable[]) null)); + assertPreconditionViolationNotNullOrEmptyFor("executables array", () -> assertAll((Executable[]) null)); } @SuppressWarnings("DataFlowIssue") @Test void assertAllWithNullExecutableCollection() { - assertPrecondition("executables collection must not be null", () -> assertAll((Collection) null)); + assertPreconditionViolationNotNullFor("executables collection", () -> assertAll((Collection) null)); } @SuppressWarnings("DataFlowIssue") @Test void assertAllWithNullExecutableStream() { - assertPrecondition("executables stream must not be null", () -> assertAll((Stream) null)); + assertPreconditionViolationNotNullFor("executables stream", () -> assertAll((Stream) null)); } @SuppressWarnings("DataFlowIssue") @Test void assertAllWithNullInExecutableArray() { - assertPrecondition("individual executables must not be null", () -> assertAll((Executable) null)); + assertPreconditionViolationNotNullFor("individual executables", () -> assertAll((Executable) null)); } @Test void assertAllWithNullInExecutableCollection() { - assertPrecondition("individual executables must not be null", () -> assertAll(asList((Executable) null))); + assertPreconditionViolationNotNullFor("individual executables", () -> assertAll(asList((Executable) null))); } @SuppressWarnings("DataFlowIssue") @Test void assertAllWithNullInExecutableStream() { - assertPrecondition("individual executables must not be null", () -> assertAll(Stream.of((Executable) null))); + assertPreconditionViolationNotNullFor("individual executables", () -> assertAll(Stream.of((Executable) null))); } @Test @@ -198,11 +198,6 @@ void assertAllWithParallelStream() { assertThat(multipleFailuresError.getFailures()).hasSize(100).doesNotContainNull(); } - private void assertPrecondition(String msg, Executable executable) { - PreconditionViolationException exception = assertThrows(PreconditionViolationException.class, executable); - assertMessageEquals(exception, msg); - } - @SafeVarargs static void assertExpectedExceptionTypes(MultipleFailuresError multipleFailuresError, Class... exceptionTypes) { diff --git a/jupiter-tests/src/test/java/org/junit/jupiter/api/AssertLinesMatchAssertionsTests.java b/jupiter-tests/src/test/java/org/junit/jupiter/api/AssertLinesMatchAssertionsTests.java index 9bfa03d7bb81..23bd6ece74b6 100644 --- a/jupiter-tests/src/test/java/org/junit/jupiter/api/AssertLinesMatchAssertionsTests.java +++ b/jupiter-tests/src/test/java/org/junit/jupiter/api/AssertLinesMatchAssertionsTests.java @@ -12,7 +12,6 @@ import static org.junit.jupiter.api.AssertLinesMatch.isFastForwardLine; import static org.junit.jupiter.api.AssertLinesMatch.parseFastForwardLimit; -import static org.junit.jupiter.api.AssertionTestUtils.assertMessageEquals; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -20,6 +19,8 @@ import static org.junit.jupiter.api.Assertions.assertLinesMatch; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotNullFor; import java.util.ArrayList; import java.util.Arrays; @@ -31,7 +32,6 @@ import java.util.stream.Stream; import org.jspecify.annotations.Nullable; -import org.junit.platform.commons.PreconditionViolationException; import org.opentest4j.AssertionFailedError; /** @@ -97,9 +97,9 @@ void assertLinesMatchUsingFastForwardMarkerWithLimit3() { @Test @SuppressWarnings({ "unchecked", "rawtypes", "DataFlowIssue" }) void assertLinesMatchWithNullFails() { - assertThrows(PreconditionViolationException.class, () -> assertLinesMatch(null, (List) null)); - assertThrows(PreconditionViolationException.class, () -> assertLinesMatch(null, Collections.emptyList())); - assertThrows(PreconditionViolationException.class, () -> assertLinesMatch(Collections.emptyList(), null)); + assertPreconditionViolationFor(() -> assertLinesMatch(null, (List) null)); + assertPreconditionViolationFor(() -> assertLinesMatch(null, Collections.emptyList())); + assertPreconditionViolationFor(() -> assertLinesMatch(Collections.emptyList(), null)); } @Test @@ -107,10 +107,8 @@ void assertLinesMatchWithNullElementsFails() { var list = List.of("1", "2", "3"); var withNullElement = Arrays.asList("1", null, "3"); // List.of() doesn't permit null values. assertDoesNotThrow(() -> assertLinesMatch(withNullElement, withNullElement)); - var e1 = assertThrows(PreconditionViolationException.class, () -> assertLinesMatch(withNullElement, list)); - assertEquals("expected line must not be null", e1.getMessage()); - var e2 = assertThrows(PreconditionViolationException.class, () -> assertLinesMatch(list, withNullElement)); - assertEquals("actual line must not be null", e2.getMessage()); + assertPreconditionViolationNotNullFor("expected line", () -> assertLinesMatch(withNullElement, list)); + assertPreconditionViolationNotNullFor("actual line", () -> assertLinesMatch(list, withNullElement)); } private void assertError(AssertionFailedError error, String expectedMessage, List expectedLines, @@ -215,12 +213,12 @@ void assertLinesMatchParseFastForwardLimit() { () -> assertEquals(9, parseFastForwardLimit(">> 9 >>")), () -> assertEquals(9, parseFastForwardLimit(" >> 9 >> ")), () -> assertEquals(9, parseFastForwardLimit(" >> 9 >> "))); - Throwable error = assertThrows(PreconditionViolationException.class, () -> parseFastForwardLimit(">>0>>")); - assertMessageEquals(error, "fast-forward(0) limit must be greater than zero"); - error = assertThrows(PreconditionViolationException.class, () -> parseFastForwardLimit(">>-1>>")); - assertMessageEquals(error, "fast-forward(-1) limit must be greater than zero"); - error = assertThrows(PreconditionViolationException.class, () -> parseFastForwardLimit(">>-2147483648>>")); - assertMessageEquals(error, "fast-forward(-2147483648) limit must be greater than zero"); + assertPreconditionViolationFor(() -> parseFastForwardLimit(">>0>>"))// + .withMessage("fast-forward(0) limit must be greater than zero"); + assertPreconditionViolationFor(() -> parseFastForwardLimit(">>-1>>"))// + .withMessage("fast-forward(-1) limit must be greater than zero"); + assertPreconditionViolationFor(() -> parseFastForwardLimit(">>-2147483648>>"))// + .withMessage("fast-forward(-2147483648) limit must be greater than zero"); } @Test diff --git a/jupiter-tests/src/test/java/org/junit/jupiter/api/DynamicTestTests.java b/jupiter-tests/src/test/java/org/junit/jupiter/api/DynamicTestTests.java index 094408a7da9e..d45427ed1621 100644 --- a/jupiter-tests/src/test/java/org/junit/jupiter/api/DynamicTestTests.java +++ b/jupiter-tests/src/test/java/org/junit/jupiter/api/DynamicTestTests.java @@ -15,6 +15,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.DynamicContainer.dynamicContainer; import static org.junit.jupiter.api.DynamicTest.dynamicTest; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -29,7 +30,6 @@ import org.jspecify.annotations.Nullable; import org.junit.jupiter.api.function.Executable; import org.junit.jupiter.api.function.ThrowingConsumer; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.commons.support.ReflectionSupport; import org.opentest4j.AssertionFailedError; @@ -50,12 +50,9 @@ void streamFromStreamPreconditions() { }; Function displayNameGenerator = Object::toString; - assertThrows(PreconditionViolationException.class, - () -> DynamicTest.stream((Stream) null, displayNameGenerator, testExecutor)); - assertThrows(PreconditionViolationException.class, - () -> DynamicTest.stream(Stream.empty(), null, testExecutor)); - assertThrows(PreconditionViolationException.class, - () -> DynamicTest.stream(Stream.empty(), displayNameGenerator, null)); + assertPreconditionViolationFor(() -> DynamicTest.stream((Stream) null, displayNameGenerator, testExecutor)); + assertPreconditionViolationFor(() -> DynamicTest.stream(Stream.empty(), null, testExecutor)); + assertPreconditionViolationFor(() -> DynamicTest.stream(Stream.empty(), displayNameGenerator, null)); } @SuppressWarnings("DataFlowIssue") @@ -65,12 +62,10 @@ void streamFromIteratorPreconditions() { }; Function displayNameGenerator = Object::toString; - assertThrows(PreconditionViolationException.class, + assertPreconditionViolationFor( () -> DynamicTest.stream((Iterator) null, displayNameGenerator, testExecutor)); - assertThrows(PreconditionViolationException.class, - () -> DynamicTest.stream(emptyIterator(), null, testExecutor)); - assertThrows(PreconditionViolationException.class, - () -> DynamicTest.stream(emptyIterator(), displayNameGenerator, null)); + assertPreconditionViolationFor(() -> DynamicTest.stream(emptyIterator(), null, testExecutor)); + assertPreconditionViolationFor(() -> DynamicTest.stream(emptyIterator(), displayNameGenerator, null)); } @SuppressWarnings("DataFlowIssue") @@ -79,9 +74,8 @@ void streamFromStreamWithNamesPreconditions() { ThrowingConsumer testExecutor = input -> { }; - assertThrows(PreconditionViolationException.class, - () -> DynamicTest.stream((Stream>) null, testExecutor)); - assertThrows(PreconditionViolationException.class, () -> DynamicTest.stream(Stream.empty(), null)); + assertPreconditionViolationFor(() -> DynamicTest.stream((Stream>) null, testExecutor)); + assertPreconditionViolationFor(() -> DynamicTest.stream(Stream.empty(), null)); } @SuppressWarnings("DataFlowIssue") @@ -90,23 +84,21 @@ void streamFromIteratorWithNamesPreconditions() { ThrowingConsumer testExecutor = input -> { }; - assertThrows(PreconditionViolationException.class, + assertPreconditionViolationFor( () -> DynamicTest.stream((Iterator>) null, testExecutor)); - assertThrows(PreconditionViolationException.class, () -> DynamicTest.stream(emptyIterator(), null)); + assertPreconditionViolationFor(() -> DynamicTest.stream(emptyIterator(), null)); } @SuppressWarnings("DataFlowIssue") @Test void streamFromStreamWithNamedExecutablesPreconditions() { - assertThrows(PreconditionViolationException.class, - () -> DynamicTest.stream((Stream) null)); + assertPreconditionViolationFor(() -> DynamicTest.stream((Stream) null)); } @SuppressWarnings("DataFlowIssue") @Test void streamFromIteratorWithNamedExecutablesPreconditions() { - assertThrows(PreconditionViolationException.class, - () -> DynamicTest.stream((Iterator) null)); + assertPreconditionViolationFor(() -> DynamicTest.stream((Iterator) null)); } @Test diff --git a/jupiter-tests/src/test/java/org/junit/jupiter/api/condition/DisabledIfEnvironmentVariableConditionTests.java b/jupiter-tests/src/test/java/org/junit/jupiter/api/condition/DisabledIfEnvironmentVariableConditionTests.java index 921f5d173e4e..02bcc9924205 100644 --- a/jupiter-tests/src/test/java/org/junit/jupiter/api/condition/DisabledIfEnvironmentVariableConditionTests.java +++ b/jupiter-tests/src/test/java/org/junit/jupiter/api/condition/DisabledIfEnvironmentVariableConditionTests.java @@ -10,16 +10,14 @@ package org.junit.jupiter.api.condition; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.condition.DisabledIfEnvironmentVariableIntegrationTests.ENIGMA; import static org.junit.jupiter.api.condition.DisabledIfEnvironmentVariableIntegrationTests.KEY1; import static org.junit.jupiter.api.condition.DisabledIfEnvironmentVariableIntegrationTests.KEY2; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotBlankFor; import org.jspecify.annotations.Nullable; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExecutionCondition; -import org.junit.platform.commons.PreconditionViolationException; /** * Unit tests for {@link DisabledIfEnvironmentVariableCondition}. @@ -68,8 +66,7 @@ void enabledBecauseAnnotationIsNotPresent() { */ @Test void blankNamedAttribute() { - Exception exception = assertThrows(PreconditionViolationException.class, this::evaluateCondition); - assertThat(exception).hasMessageContaining("The 'named' attribute must not be blank"); + assertPreconditionViolationNotBlankFor("The 'named' attribute", this::evaluateCondition); } /** @@ -77,8 +74,7 @@ void blankNamedAttribute() { */ @Test void blankMatchesAttribute() { - Exception exception = assertThrows(PreconditionViolationException.class, this::evaluateCondition); - assertThat(exception).hasMessageContaining("The 'matches' attribute must not be blank"); + assertPreconditionViolationNotBlankFor("The 'matches' attribute", this::evaluateCondition); } /** diff --git a/jupiter-tests/src/test/java/org/junit/jupiter/api/condition/DisabledIfSystemPropertyConditionTests.java b/jupiter-tests/src/test/java/org/junit/jupiter/api/condition/DisabledIfSystemPropertyConditionTests.java index 3270e6cc97da..d3466d359925 100644 --- a/jupiter-tests/src/test/java/org/junit/jupiter/api/condition/DisabledIfSystemPropertyConditionTests.java +++ b/jupiter-tests/src/test/java/org/junit/jupiter/api/condition/DisabledIfSystemPropertyConditionTests.java @@ -10,14 +10,12 @@ package org.junit.jupiter.api.condition; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotBlankFor; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExecutionCondition; -import org.junit.platform.commons.PreconditionViolationException; /** * Unit tests for {@link DisabledIfSystemPropertyCondition}. @@ -64,8 +62,7 @@ void enabledBecauseAnnotationIsNotPresent() { */ @Test void blankNamedAttribute() { - Exception exception = assertThrows(PreconditionViolationException.class, this::evaluateCondition); - assertThat(exception).hasMessageContaining("The 'named' attribute must not be blank"); + assertPreconditionViolationNotBlankFor("The 'named' attribute", this::evaluateCondition); } /** @@ -73,8 +70,7 @@ void blankNamedAttribute() { */ @Test void blankMatchesAttribute() { - Exception exception = assertThrows(PreconditionViolationException.class, this::evaluateCondition); - assertThat(exception).hasMessageContaining("The 'matches' attribute must not be blank"); + assertPreconditionViolationNotBlankFor("The 'matches' attribute", this::evaluateCondition); } /** diff --git a/jupiter-tests/src/test/java/org/junit/jupiter/api/condition/DisabledOnOsConditionTests.java b/jupiter-tests/src/test/java/org/junit/jupiter/api/condition/DisabledOnOsConditionTests.java index 2f16d47e4d77..31cff21757fd 100644 --- a/jupiter-tests/src/test/java/org/junit/jupiter/api/condition/DisabledOnOsConditionTests.java +++ b/jupiter-tests/src/test/java/org/junit/jupiter/api/condition/DisabledOnOsConditionTests.java @@ -10,8 +10,6 @@ package org.junit.jupiter.api.condition; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.condition.EnabledOnOsIntegrationTests.onAix; import static org.junit.jupiter.api.condition.EnabledOnOsIntegrationTests.onArchitecture; import static org.junit.jupiter.api.condition.EnabledOnOsIntegrationTests.onFreebsd; @@ -20,10 +18,10 @@ import static org.junit.jupiter.api.condition.EnabledOnOsIntegrationTests.onOpenbsd; import static org.junit.jupiter.api.condition.EnabledOnOsIntegrationTests.onSolaris; import static org.junit.jupiter.api.condition.EnabledOnOsIntegrationTests.onWindows; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExecutionCondition; -import org.junit.platform.commons.PreconditionViolationException; /** * Unit tests for {@link DisabledOnOsCondition}. @@ -63,8 +61,8 @@ void enabledBecauseAnnotationIsNotPresent() { */ @Test void missingOsAndArchitectureDeclaration() { - Exception exception = assertThrows(PreconditionViolationException.class, this::evaluateCondition); - assertThat(exception).hasMessageContaining("You must declare at least one OS or architecture"); + assertPreconditionViolationFor(this::evaluateCondition)// + .withMessageContaining("You must declare at least one OS or architecture"); } /** diff --git a/jupiter-tests/src/test/java/org/junit/jupiter/api/condition/EnabledIfEnvironmentVariableConditionTests.java b/jupiter-tests/src/test/java/org/junit/jupiter/api/condition/EnabledIfEnvironmentVariableConditionTests.java index 7410b433c1eb..3362bf697702 100644 --- a/jupiter-tests/src/test/java/org/junit/jupiter/api/condition/EnabledIfEnvironmentVariableConditionTests.java +++ b/jupiter-tests/src/test/java/org/junit/jupiter/api/condition/EnabledIfEnvironmentVariableConditionTests.java @@ -10,17 +10,15 @@ package org.junit.jupiter.api.condition; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.condition.EnabledIfEnvironmentVariableIntegrationTests.BOGUS; import static org.junit.jupiter.api.condition.EnabledIfEnvironmentVariableIntegrationTests.ENIGMA; import static org.junit.jupiter.api.condition.EnabledIfEnvironmentVariableIntegrationTests.KEY1; import static org.junit.jupiter.api.condition.EnabledIfEnvironmentVariableIntegrationTests.KEY2; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotBlankFor; import org.jspecify.annotations.Nullable; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExecutionCondition; -import org.junit.platform.commons.PreconditionViolationException; /** * Unit tests for {@link EnabledIfEnvironmentVariableCondition}. @@ -69,8 +67,7 @@ void enabledBecauseAnnotationIsNotPresent() { */ @Test void blankNamedAttribute() { - Exception exception = assertThrows(PreconditionViolationException.class, this::evaluateCondition); - assertThat(exception).hasMessageContaining("The 'named' attribute must not be blank"); + assertPreconditionViolationNotBlankFor("The 'named' attribute", this::evaluateCondition); } /** @@ -78,8 +75,7 @@ void blankNamedAttribute() { */ @Test void blankMatchesAttribute() { - Exception exception = assertThrows(PreconditionViolationException.class, this::evaluateCondition); - assertThat(exception).hasMessageContaining("The 'matches' attribute must not be blank"); + assertPreconditionViolationNotBlankFor("The 'matches' attribute", this::evaluateCondition); } /** diff --git a/jupiter-tests/src/test/java/org/junit/jupiter/api/condition/EnabledIfSystemPropertyConditionTests.java b/jupiter-tests/src/test/java/org/junit/jupiter/api/condition/EnabledIfSystemPropertyConditionTests.java index d9391250e47f..83c9c06602d9 100644 --- a/jupiter-tests/src/test/java/org/junit/jupiter/api/condition/EnabledIfSystemPropertyConditionTests.java +++ b/jupiter-tests/src/test/java/org/junit/jupiter/api/condition/EnabledIfSystemPropertyConditionTests.java @@ -10,14 +10,12 @@ package org.junit.jupiter.api.condition; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotBlankFor; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExecutionCondition; -import org.junit.platform.commons.PreconditionViolationException; /** * Unit tests for {@link EnabledIfSystemPropertyCondition}. @@ -64,8 +62,7 @@ void enabledBecauseAnnotationIsNotPresent() { */ @Test void blankNamedAttribute() { - Exception exception = assertThrows(PreconditionViolationException.class, this::evaluateCondition); - assertThat(exception).hasMessageContaining("The 'named' attribute must not be blank"); + assertPreconditionViolationNotBlankFor("The 'named' attribute", this::evaluateCondition); } /** @@ -73,8 +70,7 @@ void blankNamedAttribute() { */ @Test void blankMatchesAttribute() { - Exception exception = assertThrows(PreconditionViolationException.class, this::evaluateCondition); - assertThat(exception).hasMessageContaining("The 'matches' attribute must not be blank"); + assertPreconditionViolationNotBlankFor("The 'matches' attribute", this::evaluateCondition); } /** diff --git a/jupiter-tests/src/test/java/org/junit/jupiter/api/condition/EnabledOnOsConditionTests.java b/jupiter-tests/src/test/java/org/junit/jupiter/api/condition/EnabledOnOsConditionTests.java index 57ca8a41b69a..4df9aa93048f 100644 --- a/jupiter-tests/src/test/java/org/junit/jupiter/api/condition/EnabledOnOsConditionTests.java +++ b/jupiter-tests/src/test/java/org/junit/jupiter/api/condition/EnabledOnOsConditionTests.java @@ -10,8 +10,6 @@ package org.junit.jupiter.api.condition; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.condition.EnabledOnOsIntegrationTests.onAix; import static org.junit.jupiter.api.condition.EnabledOnOsIntegrationTests.onArchitecture; import static org.junit.jupiter.api.condition.EnabledOnOsIntegrationTests.onFreebsd; @@ -20,10 +18,10 @@ import static org.junit.jupiter.api.condition.EnabledOnOsIntegrationTests.onOpenbsd; import static org.junit.jupiter.api.condition.EnabledOnOsIntegrationTests.onSolaris; import static org.junit.jupiter.api.condition.EnabledOnOsIntegrationTests.onWindows; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExecutionCondition; -import org.junit.platform.commons.PreconditionViolationException; /** * Unit tests for {@link EnabledOnOsCondition}. @@ -63,8 +61,8 @@ void enabledBecauseAnnotationIsNotPresent() { */ @Test void missingOsAndArchitectureDeclaration() { - Exception exception = assertThrows(PreconditionViolationException.class, this::evaluateCondition); - assertThat(exception).hasMessageContaining("You must declare at least one OS or architecture"); + assertPreconditionViolationFor(this::evaluateCondition)// + .withMessageContaining("You must declare at least one OS or architecture"); } /** diff --git a/jupiter-tests/src/test/java/org/junit/jupiter/api/extension/support/TypeBasedParameterResolverTests.java b/jupiter-tests/src/test/java/org/junit/jupiter/api/extension/support/TypeBasedParameterResolverTests.java index a8b06d75f34b..ea4cd0c03c16 100644 --- a/jupiter-tests/src/test/java/org/junit/jupiter/api/extension/support/TypeBasedParameterResolverTests.java +++ b/jupiter-tests/src/test/java/org/junit/jupiter/api/extension/support/TypeBasedParameterResolverTests.java @@ -12,8 +12,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -31,7 +31,6 @@ import org.junit.jupiter.api.extension.ParameterContext; import org.junit.jupiter.api.extension.ParameterResolutionException; import org.junit.jupiter.api.extension.ParameterResolver; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.commons.support.ReflectionSupport; /** @@ -45,12 +44,10 @@ class TypeBasedParameterResolverTests { @Test void missingTypeTypeBasedParameterResolver() { - PreconditionViolationException exception = assertThrows(PreconditionViolationException.class, - MissingTypeTypeBasedParameterResolver::new); - assertEquals( - "Failed to discover parameter type supported by " + MissingTypeTypeBasedParameterResolver.class.getName() - + "; potentially caused by lacking parameterized type in class declaration.", - exception.getMessage()); + assertPreconditionViolationFor(MissingTypeTypeBasedParameterResolver::new)// + .withMessage("Failed to discover parameter type supported by " + + MissingTypeTypeBasedParameterResolver.class.getName() + + "; potentially caused by lacking parameterized type in class declaration."); } @Test diff --git a/jupiter-tests/src/test/java/org/junit/jupiter/engine/ReportingTests.java b/jupiter-tests/src/test/java/org/junit/jupiter/engine/ReportingTests.java index 11b4a085a73a..26cc221c09e8 100644 --- a/jupiter-tests/src/test/java/org/junit/jupiter/engine/ReportingTests.java +++ b/jupiter-tests/src/test/java/org/junit/jupiter/engine/ReportingTests.java @@ -10,8 +10,8 @@ package org.junit.jupiter.engine; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.engine.Constants.DEFAULT_TEST_INSTANCE_LIFECYCLE_PROPERTY_NAME; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass; import static org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder.request; import static org.junit.platform.launcher.core.OutputDirectoryCreators.hierarchicalOutputDirectoryCreator; @@ -35,7 +35,6 @@ import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.engine.reporting.FileEntry; /** @@ -123,20 +122,20 @@ void invalidReportData(TestReporter reporter) { Map map = new HashMap<>(); map.put("key", null); - assertThrows(PreconditionViolationException.class, () -> reporter.publishEntry(map)); + assertPreconditionViolationFor(() -> reporter.publishEntry(map)); map.clear(); map.put(null, "value"); - assertThrows(PreconditionViolationException.class, () -> reporter.publishEntry(map)); + assertPreconditionViolationFor(() -> reporter.publishEntry(map)); - assertThrows(PreconditionViolationException.class, () -> reporter.publishEntry((Map) null)); + assertPreconditionViolationFor(() -> reporter.publishEntry((Map) null)); // Key-Value pair - assertThrows(PreconditionViolationException.class, () -> reporter.publishEntry(null, "bar")); - assertThrows(PreconditionViolationException.class, () -> reporter.publishEntry("foo", null)); + assertPreconditionViolationFor(() -> reporter.publishEntry(null, "bar")); + assertPreconditionViolationFor(() -> reporter.publishEntry("foo", null)); // Value - assertThrows(PreconditionViolationException.class, () -> reporter.publishEntry((String) null)); + assertPreconditionViolationFor(() -> reporter.publishEntry((String) null)); } } diff --git a/jupiter-tests/src/test/java/org/junit/jupiter/engine/config/DefaultJupiterConfigurationTests.java b/jupiter-tests/src/test/java/org/junit/jupiter/engine/config/DefaultJupiterConfigurationTests.java index db1bcde0dd96..37f0dcc046f3 100644 --- a/jupiter-tests/src/test/java/org/junit/jupiter/engine/config/DefaultJupiterConfigurationTests.java +++ b/jupiter-tests/src/test/java/org/junit/jupiter/engine/config/DefaultJupiterConfigurationTests.java @@ -13,11 +13,11 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertAll; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS; import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_METHOD; import static org.junit.jupiter.api.io.CleanupMode.ALWAYS; import static org.junit.jupiter.engine.Constants.DEFAULT_TEST_INSTANCE_LIFECYCLE_PROPERTY_NAME; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotNullFor; import static org.junit.platform.launcher.core.OutputDirectoryCreators.dummyOutputDirectoryCreator; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -37,7 +37,6 @@ import org.junit.jupiter.api.io.TempDirFactory; import org.junit.jupiter.engine.Constants; import org.junit.jupiter.engine.descriptor.CustomDisplayNameGenerator; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.engine.ConfigurationParameters; class DefaultJupiterConfigurationTests { @@ -47,9 +46,8 @@ class DefaultJupiterConfigurationTests { @SuppressWarnings("DataFlowIssue") @Test void getDefaultTestInstanceLifecyclePreconditions() { - PreconditionViolationException exception = assertThrows(PreconditionViolationException.class, + assertPreconditionViolationNotNullFor("ConfigurationParameters", () -> new DefaultJupiterConfiguration(null, dummyOutputDirectoryCreator(), mock())); - assertThat(exception).hasMessage("ConfigurationParameters must not be null"); } @Test diff --git a/jupiter-tests/src/test/java/org/junit/jupiter/engine/descriptor/LauncherStoreFacadeTest.java b/jupiter-tests/src/test/java/org/junit/jupiter/engine/descriptor/LauncherStoreFacadeTest.java index af227e4e70ad..4280df6e1ba6 100644 --- a/jupiter-tests/src/test/java/org/junit/jupiter/engine/descriptor/LauncherStoreFacadeTest.java +++ b/jupiter-tests/src/test/java/org/junit/jupiter/engine/descriptor/LauncherStoreFacadeTest.java @@ -14,8 +14,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrowsExactly; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -23,7 +23,6 @@ import org.junit.jupiter.engine.execution.LauncherStoreFacade; import org.junit.jupiter.engine.execution.NamespaceAwareStore; import org.junit.platform.commons.JUnitException; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.engine.support.store.Namespace; import org.junit.platform.engine.support.store.NamespacedHierarchicalStore; @@ -84,7 +83,7 @@ void returnsNamespaceAwareStore() { @Test void throwsExceptionWhenNamespaceIsNull() { LauncherStoreFacade facade = new LauncherStoreFacade(requestLevelStore); - assertThrows(PreconditionViolationException.class, () -> facade.getStoreAdapter(requestLevelStore, null)); + assertPreconditionViolationFor(() -> facade.getStoreAdapter(requestLevelStore, null)); } @Test diff --git a/jupiter-tests/src/test/java/org/junit/jupiter/engine/descriptor/TestInstanceLifecycleUtilsTests.java b/jupiter-tests/src/test/java/org/junit/jupiter/engine/descriptor/TestInstanceLifecycleUtilsTests.java index fadf5adbf810..28e3eeaa2909 100644 --- a/jupiter-tests/src/test/java/org/junit/jupiter/engine/descriptor/TestInstanceLifecycleUtilsTests.java +++ b/jupiter-tests/src/test/java/org/junit/jupiter/engine/descriptor/TestInstanceLifecycleUtilsTests.java @@ -11,11 +11,11 @@ package org.junit.jupiter.engine.descriptor; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS; import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_METHOD; import static org.junit.jupiter.engine.Constants.DEFAULT_TEST_INSTANCE_LIFECYCLE_PROPERTY_NAME; import static org.junit.jupiter.engine.descriptor.TestInstanceLifecycleUtils.getTestInstanceLifecycle; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotNullFor; import static org.junit.platform.launcher.core.OutputDirectoryCreators.dummyOutputDirectoryCreator; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -31,7 +31,6 @@ import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestInstance.Lifecycle; import org.junit.jupiter.engine.config.DefaultJupiterConfiguration; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.engine.ConfigurationParameters; /** @@ -51,14 +50,10 @@ class TestInstanceLifecycleUtilsTests { @SuppressWarnings("DataFlowIssue") @Test void getTestInstanceLifecyclePreconditions() { - PreconditionViolationException exception = assertThrows(PreconditionViolationException.class, - () -> getTestInstanceLifecycle(null, - new DefaultJupiterConfiguration(mock(), dummyOutputDirectoryCreator(), mock()))); - assertThat(exception).hasMessage("testClass must not be null"); - - exception = assertThrows(PreconditionViolationException.class, - () -> getTestInstanceLifecycle(getClass(), null)); - assertThat(exception).hasMessage("configuration must not be null"); + assertPreconditionViolationNotNullFor("testClass", () -> getTestInstanceLifecycle(null, + new DefaultJupiterConfiguration(mock(), dummyOutputDirectoryCreator(), mock()))); + + assertPreconditionViolationNotNullFor("configuration", () -> getTestInstanceLifecycle(getClass(), null)); } @Test diff --git a/jupiter-tests/src/test/java/org/junit/jupiter/migrationsupport/rules/AbstractTestRuleAdapterTests.java b/jupiter-tests/src/test/java/org/junit/jupiter/migrationsupport/rules/AbstractTestRuleAdapterTests.java index 31adeb6039a0..0f3c98e30a11 100644 --- a/jupiter-tests/src/test/java/org/junit/jupiter/migrationsupport/rules/AbstractTestRuleAdapterTests.java +++ b/jupiter-tests/src/test/java/org/junit/jupiter/migrationsupport/rules/AbstractTestRuleAdapterTests.java @@ -12,12 +12,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import org.junit.jupiter.api.Test; import org.junit.jupiter.migrationsupport.rules.adapter.AbstractTestRuleAdapter; import org.junit.jupiter.migrationsupport.rules.member.TestRuleAnnotatedMember; import org.junit.platform.commons.JUnitException; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.rules.ErrorCollector; import org.junit.rules.TemporaryFolder; import org.junit.rules.TestRule; @@ -36,11 +36,9 @@ void constructionWithAssignableArgumentsIsSuccessful() { @Test void constructionWithUnassignableArgumentsFails() { - PreconditionViolationException exception = assertThrows(PreconditionViolationException.class, - () -> new TestableTestRuleAdapter(new SimpleRuleAnnotatedMember(new TemporaryFolder()), Verifier.class)); - - assertEquals(exception.getMessage(), - "class org.junit.rules.Verifier is not assignable from class org.junit.rules.TemporaryFolder"); + assertPreconditionViolationFor(() -> new TestableTestRuleAdapter( + new SimpleRuleAnnotatedMember(new TemporaryFolder()), Verifier.class)).withMessage( + "class org.junit.rules.Verifier is not assignable from class org.junit.rules.TemporaryFolder"); } @Test diff --git a/jupiter-tests/src/test/java/org/junit/jupiter/params/ParameterizedTestContextTests.java b/jupiter-tests/src/test/java/org/junit/jupiter/params/ParameterizedTestContextTests.java index 0baf170b2e56..c1cb7cde055d 100644 --- a/jupiter-tests/src/test/java/org/junit/jupiter/params/ParameterizedTestContextTests.java +++ b/jupiter-tests/src/test/java/org/junit/jupiter/params/ParameterizedTestContextTests.java @@ -11,14 +11,13 @@ package org.junit.jupiter.params; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import org.junit.jupiter.api.TestInfo; import org.junit.jupiter.params.aggregator.AggregatorIntegrationTests.CsvToPerson; import org.junit.jupiter.params.aggregator.AggregatorIntegrationTests.Person; import org.junit.jupiter.params.aggregator.ArgumentsAccessor; import org.junit.jupiter.params.provider.ValueSource; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.commons.util.ReflectionUtils; /** @@ -38,8 +37,7 @@ void validSignatures(String methodName) { @ParameterizedTest @ValueSource(strings = { "twoAggregatorsWithPrimitiveInTheMiddle", "twoAggregatorsWithTestInfoInTheMiddle" }) void invalidSignatures(String methodName) { - assertThrows(PreconditionViolationException.class, - () -> createMethodContext(InvalidTestCase.class, methodName)); + assertPreconditionViolationFor(() -> createMethodContext(InvalidTestCase.class, methodName)); } private ParameterizedTestContext createMethodContext(Class testClass, String methodName) { diff --git a/jupiter-tests/src/test/java/org/junit/jupiter/params/ParameterizedTestExtensionTests.java b/jupiter-tests/src/test/java/org/junit/jupiter/params/ParameterizedTestExtensionTests.java index b4de1991bf5f..37e6666e6047 100644 --- a/jupiter-tests/src/test/java/org/junit/jupiter/params/ParameterizedTestExtensionTests.java +++ b/jupiter-tests/src/test/java/org/junit/jupiter/params/ParameterizedTestExtensionTests.java @@ -17,6 +17,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.params.ParameterizedInvocationContextProvider.arguments; import static org.junit.jupiter.params.ParameterizedTestExtension.DECLARATION_CONTEXT_KEY; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import static org.mockito.Mockito.mock; import java.io.FileNotFoundException; @@ -48,7 +49,6 @@ import org.junit.jupiter.params.provider.ArgumentsSource; import org.junit.jupiter.params.support.ParameterDeclarations; import org.junit.platform.commons.JUnitException; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.commons.support.AnnotationSupport; import org.junit.platform.commons.util.ReflectionUtils; import org.junit.platform.engine.support.store.NamespacedHierarchicalStore; @@ -103,7 +103,7 @@ void streamsReturnedByProvidersAreClosedWhenCallingProvide() { @Test void emptyDisplayNameIsIllegal() { var extensionContext = getExtensionContextReturningSingleMethod(new EmptyDisplayNameProviderTestCase()); - assertThrows(PreconditionViolationException.class, + assertPreconditionViolationFor( () -> this.parameterizedTestExtension.provideTestTemplateInvocationContexts(extensionContext)); } @@ -121,7 +121,7 @@ void defaultDisplayNameWithEmptyStringInConfigurationIsIllegal() { }; var extensionContext = getExtensionContextReturningSingleMethod(new DefaultDisplayNameProviderTestCase(), configurationSupplier); - assertThrows(PreconditionViolationException.class, + assertPreconditionViolationFor( () -> this.parameterizedTestExtension.provideTestTemplateInvocationContexts(extensionContext)); assertEquals(1, invocations.get()); } @@ -169,9 +169,10 @@ void doesNotThrowExceptionWhenParametrizedTestDoesNotRequireArguments() { void throwsExceptionWhenParameterizedTestHasNoArgumentsSource() { var extensionContext = getExtensionContextReturningSingleMethod(new TestCaseWithNoArgumentsSource()); - assertThrows(PreconditionViolationException.class, - () -> this.parameterizedTestExtension.provideTestTemplateInvocationContexts(extensionContext), - "Configuration error: You must configure at least one arguments source for this @ParameterizedTest"); + assertPreconditionViolationFor( + () -> this.parameterizedTestExtension.provideTestTemplateInvocationContexts(extensionContext))// + .withMessage( + "Configuration error: You must configure at least one arguments source for this @ParameterizedTest"); } @Test diff --git a/jupiter-tests/src/test/java/org/junit/jupiter/params/aggregator/DefaultArgumentsAccessorTests.java b/jupiter-tests/src/test/java/org/junit/jupiter/params/aggregator/DefaultArgumentsAccessorTests.java index f9d80d934e8b..f9b8c10ea79e 100644 --- a/jupiter-tests/src/test/java/org/junit/jupiter/params/aggregator/DefaultArgumentsAccessorTests.java +++ b/jupiter-tests/src/test/java/org/junit/jupiter/params/aggregator/DefaultArgumentsAccessorTests.java @@ -16,12 +16,12 @@ import static org.junit.jupiter.api.Assertions.assertIterableEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import java.util.Arrays; import org.jspecify.annotations.Nullable; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; /** * Unit tests for {@link DefaultArgumentsAccessor}. @@ -33,21 +33,19 @@ class DefaultArgumentsAccessorTests { @SuppressWarnings("DataFlowIssue") @Test void argumentsMustNotBeNull() { - assertThrows(PreconditionViolationException.class, () -> defaultArgumentsAccessor(1, (Object[]) null)); + assertPreconditionViolationFor(() -> defaultArgumentsAccessor(1, (Object[]) null)); } @Test void indexMustNotBeNegative() { ArgumentsAccessor arguments = defaultArgumentsAccessor(1, 1, 2); - Exception exception = assertThrows(PreconditionViolationException.class, () -> arguments.get(-1)); - assertThat(exception.getMessage()).containsSubsequence("index must be", ">= 0"); + assertPreconditionViolationFor(() -> arguments.get(-1)).withMessage("index must be >= 0 and < 2"); } @Test void indexMustBeSmallerThanLength() { ArgumentsAccessor arguments = defaultArgumentsAccessor(1, 1, 2); - Exception exception = assertThrows(PreconditionViolationException.class, () -> arguments.get(2)); - assertThat(exception.getMessage()).containsSubsequence("index must be", "< 2"); + assertPreconditionViolationFor(() -> arguments.get(2)).withMessage("index must be >= 0 and < 2"); } @Test diff --git a/jupiter-tests/src/test/java/org/junit/jupiter/params/converter/TypedArgumentConverterTests.java b/jupiter-tests/src/test/java/org/junit/jupiter/params/converter/TypedArgumentConverterTests.java index c9bee1dfec78..7e54bd569130 100644 --- a/jupiter-tests/src/test/java/org/junit/jupiter/params/converter/TypedArgumentConverterTests.java +++ b/jupiter-tests/src/test/java/org/junit/jupiter/params/converter/TypedArgumentConverterTests.java @@ -13,7 +13,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.jupiter.api.Assertions.assertAll; -import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotNullFor; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -51,11 +51,11 @@ class UnitTests { @SuppressWarnings("DataFlowIssue") @Test void preconditions() { - assertPreconditionViolationFor(() -> new StringLengthArgumentConverter(null, Integer.class))// - .withMessage("sourceType must not be null"); + assertPreconditionViolationNotNullFor("sourceType", + () -> new StringLengthArgumentConverter(null, Integer.class)); - assertPreconditionViolationFor(() -> new StringLengthArgumentConverter(String.class, null))// - .withMessage("targetType must not be null"); + assertPreconditionViolationNotNullFor("targetType", + () -> new StringLengthArgumentConverter(String.class, null)); } @Test diff --git a/jupiter-tests/src/test/java/org/junit/jupiter/params/provider/CsvArgumentsProviderTests.java b/jupiter-tests/src/test/java/org/junit/jupiter/params/provider/CsvArgumentsProviderTests.java index 729bfc165b7c..49e98ea4be36 100644 --- a/jupiter-tests/src/test/java/org/junit/jupiter/params/provider/CsvArgumentsProviderTests.java +++ b/jupiter-tests/src/test/java/org/junit/jupiter/params/provider/CsvArgumentsProviderTests.java @@ -449,8 +449,9 @@ void throwsExceptionIfColumnCountExceedsHeaderCount() { banana, 2, BOOM! """).build(); - assertPreconditionViolationFor(() -> provideArguments(annotation).findAny()).withMessage( - "The number of columns (3) exceeds the number of supplied headers (2) in CSV record: [banana, 2, BOOM!]"); + assertPreconditionViolationFor(() -> provideArguments(annotation).findAny())// + .withMessage( + "The number of columns (3) exceeds the number of supplied headers (2) in CSV record: [banana, 2, BOOM!]"); } private Stream provideArguments(CsvSource annotation) { diff --git a/jupiter-tests/src/test/java/org/junit/jupiter/params/provider/CsvFileArgumentsProviderTests.java b/jupiter-tests/src/test/java/org/junit/jupiter/params/provider/CsvFileArgumentsProviderTests.java index b490ede8c610..9357e6e0ec3d 100644 --- a/jupiter-tests/src/test/java/org/junit/jupiter/params/provider/CsvFileArgumentsProviderTests.java +++ b/jupiter-tests/src/test/java/org/junit/jupiter/params/provider/CsvFileArgumentsProviderTests.java @@ -15,6 +15,9 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.params.provider.CsvArgumentsProviderTests.isCsvParseException; import static org.junit.jupiter.params.provider.MockCsvAnnotationBuilder.csvFileSource; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotEmptyFor; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotNullOrBlankFor; import static org.mockito.Mockito.doCallRealMethod; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -35,7 +38,6 @@ import org.junit.jupiter.params.provider.CsvFileArgumentsProvider.InputStreamProvider; import org.junit.jupiter.params.support.ParameterNameAndArgument; import org.junit.platform.commons.JUnitException; -import org.junit.platform.commons.PreconditionViolationException; /** * @since 5.0 @@ -115,12 +117,9 @@ void throwsExceptionIfBothDelimitersAreSimultaneouslySet() { .delimiterString(";")// .build(); - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments(annotation, "foo").findAny()); - - assertThat(exception)// - .hasMessageStartingWith("The delimiter and delimiterString attributes cannot be set simultaneously in")// - .hasMessageContaining("CsvFileSource"); + assertPreconditionViolationFor(() -> provideArguments(annotation, "foo").findAny())// + .withMessageStartingWith("The delimiter and delimiterString attributes cannot be set simultaneously in")// + .withMessageContaining("CsvFileSource"); } @Test @@ -326,10 +325,8 @@ void throwsExceptionForMissingClasspathResource() { .resources("/does-not-exist.csv")// .build(); - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments(new CsvFileArgumentsProvider(), annotation).toArray()); - - assertThat(exception).hasMessageContaining("Classpath resource [/does-not-exist.csv] does not exist"); + assertPreconditionViolationFor(() -> provideArguments(new CsvFileArgumentsProvider(), annotation).toArray())// + .withMessageContaining("Classpath resource [/does-not-exist.csv] does not exist"); } @Test @@ -338,10 +335,8 @@ void throwsExceptionForBlankClasspathResource() { .resources(" ")// .build(); - var exception = assertThrows(PreconditionViolationException.class, + assertPreconditionViolationNotNullOrBlankFor("Classpath resource [ ]", () -> provideArguments(new CsvFileArgumentsProvider(), annotation).toArray()); - - assertThat(exception).hasMessageContaining("Classpath resource [ ] must not be null or blank"); } @Test @@ -362,10 +357,8 @@ void throwsExceptionForBlankFile() { .files(" ")// .build(); - var exception = assertThrows(PreconditionViolationException.class, + assertPreconditionViolationNotNullOrBlankFor("File [ ]", () -> provideArguments(new CsvFileArgumentsProvider(), annotation).toArray()); - - assertThat(exception).hasMessageContaining("File [ ] must not be null or blank"); } @Test @@ -375,10 +368,8 @@ void throwsExceptionIfResourcesAndFilesAreEmpty() { .files()// .build(); - var exception = assertThrows(PreconditionViolationException.class, + assertPreconditionViolationNotEmptyFor("Resources or files", () -> provideArguments(new CsvFileArgumentsProvider(), annotation).toArray()); - - assertThat(exception).hasMessageContaining("Resources or files must not be empty"); } @Test @@ -388,12 +379,9 @@ void throwsExceptionForInvalidCharset() { .resources("/bogus-charset.csv")// .build(); - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments(new CsvFileArgumentsProvider(), annotation).toArray()); - - assertThat(exception)// - .hasMessageContaining("The charset supplied in Mock for CsvFileSource")// - .hasMessageEndingWith("is invalid"); + assertPreconditionViolationFor(() -> provideArguments(new CsvFileArgumentsProvider(), annotation).toArray())// + .withMessageContaining("The charset supplied in Mock for CsvFileSource")// + .withMessageEndingWith("is invalid"); } @Test @@ -488,11 +476,9 @@ void throwsExceptionWhenMaxCharsPerColumnIsNotPositiveNumberOrMinusOne(int maxCh .files(csvFile.toAbsolutePath().toString())// .build(); - var exception = assertThrows(PreconditionViolationException.class, // - () -> provideArguments(new CsvFileArgumentsProvider(), annotation).findAny()); - - assertThat(exception)// - .hasMessageStartingWith("maxCharsPerColumn must be a positive number or -1: " + maxCharsPerColumn); + assertPreconditionViolationFor( + () -> provideArguments(new CsvFileArgumentsProvider(), annotation).findAny()).withMessageStartingWith( + "maxCharsPerColumn must be a positive number or -1: " + maxCharsPerColumn); } @Test diff --git a/jupiter-tests/src/test/java/org/junit/jupiter/params/provider/EnumArgumentsProviderTests.java b/jupiter-tests/src/test/java/org/junit/jupiter/params/provider/EnumArgumentsProviderTests.java index 02ba3d442a7b..5d12d5ee6037 100644 --- a/jupiter-tests/src/test/java/org/junit/jupiter/params/provider/EnumArgumentsProviderTests.java +++ b/jupiter-tests/src/test/java/org/junit/jupiter/params/provider/EnumArgumentsProviderTests.java @@ -16,6 +16,7 @@ import static org.junit.jupiter.params.provider.EnumArgumentsProviderTests.EnumWithFourConstants.BAZ; import static org.junit.jupiter.params.provider.EnumArgumentsProviderTests.EnumWithFourConstants.FOO; import static org.junit.jupiter.params.provider.EnumArgumentsProviderTests.EnumWithFourConstants.QUX; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -28,7 +29,6 @@ import org.junit.jupiter.params.provider.EnumSource.Mode; import org.junit.jupiter.params.support.ParameterDeclaration; import org.junit.jupiter.params.support.ParameterDeclarations; -import org.junit.platform.commons.PreconditionViolationException; /** * @since 5.0 @@ -62,23 +62,22 @@ void provideAllEnumConstantsWithNamingAll() { @Test void duplicateConstantNameIsDetected() { - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments(EnumWithFourConstants.class, "FOO", "BAR", "FOO").findAny()); - assertThat(exception).hasMessageContaining("Duplicate enum constant name(s) found"); + assertPreconditionViolationFor( + () -> provideArguments(EnumWithFourConstants.class, "FOO", "BAR", "FOO").findAny()).withMessageContaining( + "Duplicate enum constant name(s) found"); } @Test void invalidConstantNameIsDetected() { - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments(EnumWithFourConstants.class, "FO0", "B4R").findAny()); - assertThat(exception).hasMessageContaining("Invalid enum constant name(s) in"); + assertPreconditionViolationFor( + () -> provideArguments(EnumWithFourConstants.class, "FO0", "B4R").findAny()).withMessageContaining( + "Invalid enum constant name(s) in"); } @Test void invalidPatternIsDetected() { - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments(EnumWithFourConstants.class, Mode.MATCH_ALL, "(", ")").findAny()); - assertThat(exception).hasMessageContaining("Pattern compilation failed"); + assertPreconditionViolationFor(() -> provideArguments(EnumWithFourConstants.class, Mode.MATCH_ALL, "(", + ")").findAny()).withMessageContaining("Pattern compilation failed"); } @Test @@ -99,18 +98,16 @@ void incorrectParameterTypeIsDetected() { when(firstParameterDeclaration.getParameterType()).thenAnswer(__ -> Object.class); when(parameters.getFirst()).thenReturn(Optional.of(firstParameterDeclaration)); - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments(NullEnum.class).findAny()); - assertThat(exception).hasMessageStartingWith("First parameter must reference an Enum type"); + assertPreconditionViolationFor(() -> provideArguments(NullEnum.class).findAny()).withMessageStartingWith( + "First parameter must reference an Enum type"); } @Test void methodsWithoutParametersAreDetected() { when(parameters.getSourceElementDescription()).thenReturn("method"); - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments(NullEnum.class).findAny()); - assertThat(exception).hasMessageStartingWith("There must be at least one declared parameter for method"); + assertPreconditionViolationFor(() -> provideArguments(NullEnum.class).findAny()).withMessageStartingWith( + "There must be at least one declared parameter for method"); } @Test @@ -150,9 +147,8 @@ void providesNoEnumConstant() { @Test void invalidConstantNameIsDetectedInRange() { - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments(EnumWithFourConstants.class, "FOO", "BAZ", Mode.EXCLUDE, "QUX").findAny()); - assertThat(exception).hasMessageContaining("Invalid enum constant name(s) in"); + assertPreconditionViolationFor(() -> provideArguments(EnumWithFourConstants.class, "FOO", "BAZ", Mode.EXCLUDE, + "QUX").findAny()).withMessageContaining("Invalid enum constant name(s) in"); } @Test @@ -171,16 +167,14 @@ void invalidEndingRangeIsDetected() { @Test void invalidRangeOrderIsDetected() { - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments(EnumWithFourConstants.class, "BAR", "FOO", Mode.INCLUDE).findAny()); - assertThat(exception).hasMessageContaining("Invalid enum range"); + assertPreconditionViolationFor(() -> provideArguments(EnumWithFourConstants.class, "BAR", "FOO", + Mode.INCLUDE).findAny()).withMessageContaining("Invalid enum range"); } @Test void invalidRangeIsDetectedWhenEnumWithNoConstantIsProvided() { - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments(EnumWithNoConstant.class, "BAR", "FOO", Mode.INCLUDE).findAny()); - assertThat(exception).hasMessageContaining("No enum constant"); + assertPreconditionViolationFor(() -> provideArguments(EnumWithNoConstant.class, "BAR", "FOO", + Mode.INCLUDE).findAny()).withMessageContaining("No enum constant"); } static class TestCase { diff --git a/jupiter-tests/src/test/java/org/junit/jupiter/params/provider/FieldArgumentsProviderTests.java b/jupiter-tests/src/test/java/org/junit/jupiter/params/provider/FieldArgumentsProviderTests.java index 9271b3a97141..5f4de082012f 100644 --- a/jupiter-tests/src/test/java/org/junit/jupiter/params/provider/FieldArgumentsProviderTests.java +++ b/jupiter-tests/src/test/java/org/junit/jupiter/params/provider/FieldArgumentsProviderTests.java @@ -14,6 +14,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.engine.extension.MutableExtensionRegistry.createRegistryWithDefaultExtensions; import static org.junit.platform.commons.support.ReflectionSupport.findMethod; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import static org.mockito.Mockito.doCallRealMethod; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -37,7 +38,6 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.support.ParameterDeclarations; import org.junit.platform.commons.JUnitException; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.commons.support.ReflectionSupport; import org.junit.platform.commons.test.TestClassLoader; @@ -317,11 +317,12 @@ class ErrorCases { @Test void throwsExceptionWhenNonStaticLocalFieldIsReferencedWithLifecyclePerMethodSemantics() { var lifecyclePerClass = false; - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments(NonStaticTestCase.class, lifecyclePerClass, - "nonStaticStringStreamSupplier").toArray()); - - assertStaticIsRequired(exception); + assertPreconditionViolationFor(() -> provideArguments(NonStaticTestCase.class, lifecyclePerClass, + "nonStaticStringStreamSupplier").toArray())// + .withMessageContainingAll("Field '", + "' must be static: local @FieldSource fields must be static ", + "unless the PER_CLASS @TestInstance lifecycle mode is used; ", + "external @FieldSource fields must always be static."); } @Test @@ -329,10 +330,10 @@ void throwsExceptionWhenNonStaticExternalFieldIsReferencedWithLifecyclePerMethod var factoryClass = NonStaticTestCase.class.getName(); var field = factoryClass + "#nonStaticStringStreamSupplier"; var lifecyclePerClass = false; - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments(TestCase.class, lifecyclePerClass, field).toArray()); - - assertStaticIsRequired(exception); + assertPreconditionViolationFor(() -> provideArguments(TestCase.class, lifecyclePerClass, field).toArray())// + .withMessageContainingAll("Field '", "' must be static: local @FieldSource fields must be static ", + "unless the PER_CLASS @TestInstance lifecycle mode is used; ", + "external @FieldSource fields must always be static."); } @Test @@ -340,29 +341,20 @@ void throwsExceptionWhenNonStaticExternalFieldIsReferencedWithLifecyclePerClassS var factoryClass = NonStaticTestCase.class.getName(); var field = factoryClass + "#nonStaticStringStreamSupplier"; boolean lifecyclePerClass = true; - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments(TestCase.class, lifecyclePerClass, field).toArray()); - - assertStaticIsRequired(exception); - } - - private static void assertStaticIsRequired(PreconditionViolationException exception) { - assertThat(exception).hasMessageContainingAll("Field '", - "' must be static: local @FieldSource fields must be static ", - "unless the PER_CLASS @TestInstance lifecycle mode is used; ", - "external @FieldSource fields must always be static."); + assertPreconditionViolationFor(() -> provideArguments(TestCase.class, lifecyclePerClass, field).toArray())// + .withMessageContainingAll("Field '", "' must be static: local @FieldSource fields must be static ", + "unless the PER_CLASS @TestInstance lifecycle mode is used; ", + "external @FieldSource fields must always be static."); } @ParameterizedTest @ValueSource(strings = { "org.example.MyUtils", "org.example.MyUtils#", "#fieldName" }) void throwsExceptionWhenFullyQualifiedFieldNameSyntaxIsInvalid(String fieldName) { - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments(fieldName).toArray()); - - assertThat(exception.getMessage()).isEqualTo(""" - [%s] is not a valid fully qualified field name: \ - it must start with a fully qualified class name followed by a \ - '#' and then the field name.""", fieldName, TestCase.class.getName()); + assertPreconditionViolationFor(() -> provideArguments(fieldName).toArray())// + .withMessage(""" + [%s] is not a valid fully qualified field name: \ + it must start with a fully qualified class name followed by a \ + '#' and then the field name.""", fieldName, TestCase.class.getName()); } @Test @@ -375,11 +367,9 @@ void throwsExceptionWhenClassForExternalFieldCannotBeLoaded() { @Test void throwsExceptionWhenLocalFieldDoesNotExist() { - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments("nonExistentField").toArray()); - - assertThat(exception.getMessage()).isEqualTo("Could not find field named [nonExistentField] in class [%s]", - TestCase.class.getName()); + assertPreconditionViolationFor(() -> provideArguments("nonExistentField").toArray())// + .withMessage("Could not find field named [nonExistentField] in class [%s]", + TestCase.class.getName()); } @ParameterizedTest @@ -387,11 +377,8 @@ void throwsExceptionWhenLocalFieldDoesNotExist() { void throwsExceptionWhenExternalFieldDoesNotExist(String fieldName) { String factoryClass = ExternalFields.class.getName(); - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments(factoryClass + "#" + fieldName).toArray()); - - assertThat(exception.getMessage()).isEqualTo("Could not find field named [%s] in class [%s]", fieldName, - factoryClass); + assertPreconditionViolationFor(() -> provideArguments(factoryClass + "#" + fieldName).toArray())// + .withMessage("Could not find field named [%s] in class [%s]", fieldName, factoryClass); } @Test @@ -399,10 +386,8 @@ void throwsExceptionWhenLocalFieldHasNullValue() { String field = "nullList"; String factoryClass = TestCase.class.getName(); - var exception = assertThrows(PreconditionViolationException.class, () -> provideArguments(field).toArray()); - - assertThat(exception.getMessage()).isEqualTo("The value of field [%s] in class [%s] must not be null", - field, factoryClass); + assertPreconditionViolationFor(() -> provideArguments(field).toArray())// + .withMessage("The value of field [%s] in class [%s] must not be null", field, factoryClass); } @Test @@ -410,10 +395,9 @@ void throwsExceptionWhenLocalFieldHasInvalidReturnType() { String field = "object"; String factoryClass = TestCase.class.getName(); - var exception = assertThrows(PreconditionViolationException.class, () -> provideArguments(field).toArray()); - - assertThat(exception.getMessage()).isEqualTo( - "The value of field [%s] in class [%s] must be convertible to a Stream", field, factoryClass); + assertPreconditionViolationFor(() -> provideArguments(field).toArray())// + .withMessage("The value of field [%s] in class [%s] must be convertible to a Stream", field, + factoryClass); } @Test @@ -422,11 +406,9 @@ void throwsExceptionWhenExternalFieldHasInvalidReturnType() { String fieldName = "object"; String field = factoryClass + "#" + fieldName; - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments(TestCase.class, false, field).toArray()); - - assertThat(exception.getMessage()).isEqualTo( - "The value of field [%s] in class [%s] must be convertible to a Stream", fieldName, factoryClass); + assertPreconditionViolationFor(() -> provideArguments(TestCase.class, false, field).toArray())// + .withMessage("The value of field [%s] in class [%s] must be convertible to a Stream", fieldName, + factoryClass); } @ParameterizedTest @@ -434,10 +416,8 @@ void throwsExceptionWhenExternalFieldHasInvalidReturnType() { void throwsExceptionWhenLocalFieldHasStreamReturnType(String field) { String factoryClass = TestCase.class.getName(); - var exception = assertThrows(PreconditionViolationException.class, () -> provideArguments(field).toArray()); - - assertThat(exception.getMessage()).isEqualTo("The value of field [%s] in class [%s] must not be a stream", - field, factoryClass); + assertPreconditionViolationFor(() -> provideArguments(field).toArray())// + .withMessage("The value of field [%s] in class [%s] must not be a stream", field, factoryClass); } @Test @@ -445,10 +425,8 @@ void throwsExceptionWhenLocalFieldHasIteratorReturnType() { String field = "iterator"; String factoryClass = TestCase.class.getName(); - var exception = assertThrows(PreconditionViolationException.class, () -> provideArguments(field).toArray()); - - assertThat(exception.getMessage()).isEqualTo( - "The value of field [%s] in class [%s] must not be an Iterator", field, factoryClass); + assertPreconditionViolationFor(() -> provideArguments(field).toArray())// + .withMessage("The value of field [%s] in class [%s] must not be an Iterator", field, factoryClass); } } diff --git a/jupiter-tests/src/test/java/org/junit/jupiter/params/provider/MethodArgumentsProviderTests.java b/jupiter-tests/src/test/java/org/junit/jupiter/params/provider/MethodArgumentsProviderTests.java index b030b3520252..c6c2568544e8 100644 --- a/jupiter-tests/src/test/java/org/junit/jupiter/params/provider/MethodArgumentsProviderTests.java +++ b/jupiter-tests/src/test/java/org/junit/jupiter/params/provider/MethodArgumentsProviderTests.java @@ -13,6 +13,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.engine.extension.MutableExtensionRegistry.createRegistryWithDefaultExtensions; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import static org.junit.platform.commons.util.ReflectionUtils.findMethod; import static org.mockito.Mockito.doCallRealMethod; import static org.mockito.Mockito.mock; @@ -42,7 +43,6 @@ import org.junit.jupiter.engine.extension.MutableExtensionRegistry; import org.junit.jupiter.params.ParameterizedTest; import org.junit.platform.commons.JUnitException; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.commons.test.TestClassLoader; import org.junit.platform.commons.util.ReflectionUtils; @@ -179,11 +179,15 @@ void providesArgumentsUsingListOfObjectArrays() { @Test void throwsExceptionWhenNonStaticLocalFactoryMethodIsReferencedWithLifecyclePerMethodSemantics() { var lifecyclePerClass = false; - var exception = assertThrows(PreconditionViolationException.class, + assertPreconditionViolationFor(// () -> provideArguments(NonStaticTestCase.class, lifecyclePerClass, - "nonStaticStringStreamProvider").toArray()); - - assertStaticIsRequired(exception); + "nonStaticStringStreamProvider").toArray())// + .withMessageContainingAll(// + "Method '", // + "' must be static: local factory methods must be static ", // + "unless the PER_CLASS @TestInstance lifecycle mode is used; ", // + "external factory methods must always be static."// + ); } @Test @@ -191,10 +195,14 @@ void throwsExceptionWhenNonStaticExternalFactoryMethodIsReferencedWithLifecycleP var factoryClass = NonStaticTestCase.class.getName(); var factoryMethod = factoryClass + "#nonStaticStringStreamProvider"; var lifecyclePerClass = false; - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments(TestCase.class, lifecyclePerClass, factoryMethod).toArray()); - - assertStaticIsRequired(exception); + assertPreconditionViolationFor(// + () -> provideArguments(TestCase.class, lifecyclePerClass, factoryMethod).toArray())// + .withMessageContainingAll(// + "Method '", // + "' must be static: local factory methods must be static ", // + "unless the PER_CLASS @TestInstance lifecycle mode is used; ", // + "external factory methods must always be static."// + ); } @Test @@ -202,17 +210,14 @@ void throwsExceptionWhenNonStaticExternalFactoryMethodIsReferencedWithLifecycleP var factoryClass = NonStaticTestCase.class.getName(); var factoryMethod = factoryClass + "#nonStaticStringStreamProvider"; boolean lifecyclePerClass = true; - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments(TestCase.class, lifecyclePerClass, factoryMethod).toArray()); - - assertStaticIsRequired(exception); - } - - private static void assertStaticIsRequired(PreconditionViolationException exception) { - assertThat(exception).hasMessageContainingAll("Method '", - "' must be static: local factory methods must be static ", - "unless the PER_CLASS @TestInstance lifecycle mode is used; ", - "external factory methods must always be static."); + assertPreconditionViolationFor(// + () -> provideArguments(TestCase.class, lifecyclePerClass, factoryMethod).toArray())// + .withMessageContainingAll(// + "Method '", // + "' must be static: local factory methods must be static ", // + "unless the PER_CLASS @TestInstance lifecycle mode is used; ", // + "external factory methods must always be static."// + ); } @Test @@ -480,23 +485,19 @@ in class [org.junit.jupiter.params.provider.MethodArgumentsProviderTests$TestCas @Test void failsToProvideArgumentsUsingFullyQualifiedNameSpecifyingIncorrectParameterType() { String method = TestCase.class.getName() + "#stringStreamProviderWithParameter(java.lang.Integer)"; - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments(method).toArray()); - - assertThat(exception).hasMessage(""" - Could not find factory method [stringStreamProviderWithParameter(java.lang.Integer)] in \ - class [org.junit.jupiter.params.provider.MethodArgumentsProviderTests$TestCase]"""); + assertPreconditionViolationFor(() -> provideArguments(method).toArray())// + .withMessage(""" + Could not find factory method [stringStreamProviderWithParameter(java.lang.Integer)] in \ + class [org.junit.jupiter.params.provider.MethodArgumentsProviderTests$TestCase]"""); } @Test void failsToProvideArgumentsUsingLocalQualifiedNameSpecifyingIncorrectParameterType() { var method = "stringStreamProviderWithParameter(java.lang.Integer)"; - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments(this.testMethod, method).toArray()); - - assertThat(exception).hasMessage(""" - Could not find factory method [stringStreamProviderWithParameter(java.lang.Integer)] in \ - class [org.junit.jupiter.params.provider.MethodArgumentsProviderTests$TestCase]"""); + assertPreconditionViolationFor(() -> provideArguments(this.testMethod, method).toArray())// + .withMessage(""" + Could not find factory method [stringStreamProviderWithParameter(java.lang.Integer)] in \ + class [org.junit.jupiter.params.provider.MethodArgumentsProviderTests$TestCase]"""); } @ParameterizedTest @@ -580,13 +581,12 @@ class ErrorCases { @Test void throwsExceptionWhenFullyQualifiedMethodNameSyntaxIsInvalid() { - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments("org.example.wrongSyntax").toArray()); - - assertThat(exception.getMessage()).isEqualTo( - "[org.example.wrongSyntax] is not a valid fully qualified method name: " - + "it must start with a fully qualified class name followed by a '#' and then the method name, " - + "optionally followed by a parameter list enclosed in parentheses."); + assertPreconditionViolationFor(() -> provideArguments("org.example.wrongSyntax").toArray())// + .withMessage(// + "[org.example.wrongSyntax] is not a valid fully qualified method name: "// + + "it must start with a fully qualified class name followed by a '#' and then the method name, "// + + "optionally followed by a parameter list enclosed in parentheses."// + ); } @Test @@ -601,61 +601,49 @@ void throwsExceptionWhenClassForExternalFactoryMethodCannotBeLoaded() { void throwsExceptionWhenExternalFactoryMethodDoesNotExist() { String factoryClass = ExternalFactoryMethods.class.getName(); - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments(factoryClass + "#nonExistentMethod").toArray()); - - assertThat(exception.getMessage()).isEqualTo( - "Could not find factory method [nonExistentMethod] in class [%s]", factoryClass); + assertPreconditionViolationFor(() -> provideArguments(factoryClass + "#nonExistentMethod").toArray())// + .withMessage("Could not find factory method [nonExistentMethod] in class [%s]", factoryClass); } @Test void throwsExceptionWhenLocalFactoryMethodDoesNotExist() { - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments("nonExistentMethod").toArray()); - - assertThat(exception.getMessage()).isEqualTo( - "Could not find factory method [nonExistentMethod] in class [%s]", TestCase.class.getName()); + assertPreconditionViolationFor(() -> provideArguments("nonExistentMethod").toArray())// + .withMessage("Could not find factory method [nonExistentMethod] in class [%s]", + TestCase.class.getName()); } @Test void throwsExceptionWhenExternalFactoryMethodAcceptingSingleArgumentDoesNotExist() { String factoryClass = ExternalFactoryMethods.class.getName(); - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments(factoryClass + "#nonExistentMethod(int)").toArray()); - - assertThat(exception.getMessage()).isEqualTo( - "Could not find factory method [nonExistentMethod(int)] in class [%s]", factoryClass); + assertPreconditionViolationFor(() -> provideArguments(factoryClass + "#nonExistentMethod(int)").toArray())// + .withMessage("Could not find factory method [nonExistentMethod(int)] in class [%s]", factoryClass); } @Test void throwsExceptionWhenLocalFactoryMethodAcceptingSingleArgumentDoesNotExist() { - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments("nonExistentMethod(int)").toArray()); - - assertThat(exception.getMessage()).isEqualTo( - "Could not find factory method [nonExistentMethod(int)] in class [%s]", TestCase.class.getName()); + assertPreconditionViolationFor(() -> provideArguments("nonExistentMethod(int)").toArray())// + .withMessage("Could not find factory method [nonExistentMethod(int)] in class [%s]", + TestCase.class.getName()); } @Test void throwsExceptionWhenExternalFactoryMethodAcceptingMultipleArgumentsDoesNotExist() { String factoryClass = ExternalFactoryMethods.class.getName(); - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments(factoryClass + "#nonExistentMethod(int, java.lang.String)").toArray()); - - assertThat(exception.getMessage()).isEqualTo( - "Could not find factory method [nonExistentMethod(int, java.lang.String)] in class [%s]", factoryClass); + assertPreconditionViolationFor( + () -> provideArguments(factoryClass + "#nonExistentMethod(int, java.lang.String)").toArray())// + .withMessage( + "Could not find factory method [nonExistentMethod(int, java.lang.String)] in class [%s]", + factoryClass); } @Test void throwsExceptionWhenLocalFactoryMethodAcceptingMultipleArgumentsDoesNotExist() { - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments("nonExistentMethod(java.lang.String,int)").toArray()); - - assertThat(exception.getMessage()).isEqualTo( - "Could not find factory method [nonExistentMethod(java.lang.String,int)] in class [%s]", - TestCase.class.getName()); + assertPreconditionViolationFor(() -> provideArguments("nonExistentMethod(java.lang.String,int)").toArray())// + .withMessage( + "Could not find factory method [nonExistentMethod(java.lang.String,int)] in class [%s]", + TestCase.class.getName()); } @Test @@ -664,14 +652,12 @@ void throwsExceptionWhenExternalFactoryMethodHasInvalidReturnType() { String factoryClass = ExternalFactoryMethods.class.getName(); String factoryMethod = factoryClass + "#factoryWithInvalidReturnType"; - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments(TestCase.class, false, factoryMethod).toArray()); - - assertThat(exception).hasMessage(""" - Could not find valid factory method [%s] for test class [%s] \ - but found the following invalid candidate: \ - static java.lang.Object %s.factoryWithInvalidReturnType()\ - """.formatted(factoryMethod, testClass, factoryClass)); + assertPreconditionViolationFor(() -> provideArguments(TestCase.class, false, factoryMethod).toArray())// + .withMessage(""" + Could not find valid factory method [%s] for test class [%s] \ + but found the following invalid candidate: \ + static java.lang.Object %s.factoryWithInvalidReturnType()\ + """.formatted(factoryMethod, testClass, factoryClass)); } @Test @@ -680,14 +666,12 @@ void throwsExceptionWhenLocalFactoryMethodHasInvalidReturnType() { String factoryClass = testClass; String factoryMethod = "factoryWithInvalidReturnType"; - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments(factoryMethod).toArray()); - - assertThat(exception.getMessage())// - .containsSubsequence("Could not find valid factory method [" + factoryMethod + "] for test class [", - factoryClass + "]", // - "but found the following invalid candidate: ", // - "static java.lang.Object " + factoryClass + ".factoryWithInvalidReturnType()"); + assertPreconditionViolationFor(() -> provideArguments(factoryMethod).toArray())// + .withMessage(""" + Could not find valid factory method [%s] for test class [%s] \ + but found the following invalid candidate: \ + static java.lang.Object %s.factoryWithInvalidReturnType()\ + """.formatted(factoryMethod, factoryClass, factoryClass)); } @Test @@ -696,14 +680,12 @@ void throwsExceptionWhenMultipleDefaultFactoryMethodCandidatesExist() { var methodName = "test"; var testMethod = findMethod(testClass, methodName, String.class).get(); - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments(testClass, testMethod, false, "").toArray()); - - assertThat(exception.getMessage()).contains(// - "2 factory methods named [test] were found in class [", testClass.getName() + "]: ", // - "$MultipleDefaultFactoriesTestCase.test()", // - "$MultipleDefaultFactoriesTestCase.test(int)"// - ); + assertPreconditionViolationFor(() -> provideArguments(testClass, testMethod, false, "").toArray())// + .withMessageContainingAll(// + "2 factory methods named [test] were found in class [", testClass.getName() + "]: ", // + "$MultipleDefaultFactoriesTestCase.test()", // + "$MultipleDefaultFactoriesTestCase.test(int)"// + ); } @Test @@ -712,15 +694,13 @@ void throwsExceptionWhenMultipleInvalidDefaultFactoryMethodCandidatesExist() { var methodName = "test"; var testMethod = findMethod(testClass, methodName, String.class).get(); - var exception = assertThrows(PreconditionViolationException.class, - () -> provideArguments(testClass, testMethod, false, "").toArray()); - - assertThat(exception.getMessage()).contains(// - "Could not find valid factory method [test] in class [", testClass.getName() + "]", // - "but found the following invalid candidates: ", // - "$MultipleInvalidDefaultFactoriesTestCase.test()", // - "$MultipleInvalidDefaultFactoriesTestCase.test(int)"// - ); + assertPreconditionViolationFor(() -> provideArguments(testClass, testMethod, false, "").toArray())// + .withMessageContainingAll(// + "Could not find valid factory method [test] in class [", testClass.getName() + "]", // + "but found the following invalid candidates: ", // + "$MultipleInvalidDefaultFactoriesTestCase.test()", // + "$MultipleInvalidDefaultFactoriesTestCase.test(int)"// + ); } } diff --git a/jupiter-tests/src/test/java/org/junit/jupiter/params/provider/ValueArgumentsProviderTests.java b/jupiter-tests/src/test/java/org/junit/jupiter/params/provider/ValueArgumentsProviderTests.java index a601714565e8..334888fb10e2 100644 --- a/jupiter-tests/src/test/java/org/junit/jupiter/params/provider/ValueArgumentsProviderTests.java +++ b/jupiter-tests/src/test/java/org/junit/jupiter/params/provider/ValueArgumentsProviderTests.java @@ -11,7 +11,7 @@ package org.junit.jupiter.params.provider; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -19,7 +19,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtensionContext; -import org.junit.platform.commons.PreconditionViolationException; /** * @since 5.0 @@ -28,22 +27,18 @@ class ValueArgumentsProviderTests { @Test void multipleInputsAreNotAllowed() { - var exception = assertThrows(PreconditionViolationException.class, + assertPreconditionViolationFor( () -> provideArguments(new short[1], new byte[0], new int[1], new long[0], new float[0], new double[0], - new char[0], new boolean[0], new String[0], new Class[0]).findAny()); - - assertThat(exception).hasMessageContaining( - "Exactly one type of input must be provided in the @ValueSource annotation, but there were 2"); + new char[0], new boolean[0], new String[0], new Class[0]).findAny()).withMessageContaining( + "Exactly one type of input must be provided in the @ValueSource annotation, but there were 2"); } @Test void onlyEmptyInputsAreNotAllowed() { - var exception = assertThrows(PreconditionViolationException.class, + assertPreconditionViolationFor( () -> provideArguments(new short[0], new byte[0], new int[0], new long[0], new float[0], new double[0], - new char[0], new boolean[0], new String[0], new Class[0]).findAny()); - - assertThat(exception).hasMessageContaining( - "Exactly one type of input must be provided in the @ValueSource annotation, but there were 0"); + new char[0], new boolean[0], new String[0], new Class[0]).findAny()).withMessageContaining( + "Exactly one type of input must be provided in the @ValueSource annotation, but there were 0"); } /** diff --git a/platform-tests/src/test/java/org/junit/platform/commons/support/AnnotationSupportTests.java b/platform-tests/src/test/java/org/junit/platform/commons/support/AnnotationSupportTests.java index d4eed95f0d03..f20bf52c41d2 100644 --- a/platform-tests/src/test/java/org/junit/platform/commons/support/AnnotationSupportTests.java +++ b/platform-tests/src/test/java/org/junit/platform/commons/support/AnnotationSupportTests.java @@ -13,7 +13,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotNullFor; import java.lang.annotation.ElementType; @@ -26,7 +26,6 @@ import org.jspecify.annotations.NullUnmarked; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.commons.util.AnnotationUtils; import org.junit.platform.commons.util.ReflectionUtils; @@ -191,9 +190,9 @@ void findRepeatableAnnotationsDelegates() throws Throwable { var bMethod = Probe.class.getDeclaredMethod("bMethod"); assertEquals(AnnotationUtils.findRepeatableAnnotations(bMethod, Tag.class), AnnotationSupport.findRepeatableAnnotations(bMethod, Tag.class)); - Object expected = assertThrows(PreconditionViolationException.class, + var expected = assertPreconditionViolationFor( () -> AnnotationUtils.findRepeatableAnnotations(bMethod, Override.class)); - Object actual = assertThrows(PreconditionViolationException.class, + var actual = assertPreconditionViolationFor( () -> AnnotationSupport.findRepeatableAnnotations(bMethod, Override.class)); assertSame(expected.getClass(), actual.getClass(), "expected same exception class"); assertEquals(expected.toString(), actual.toString(), "expected equal exception toString representation"); diff --git a/platform-tests/src/test/java/org/junit/platform/commons/support/ReflectionSupportTests.java b/platform-tests/src/test/java/org/junit/platform/commons/support/ReflectionSupportTests.java index 3ee9ba666485..47c23ee56bc6 100644 --- a/platform-tests/src/test/java/org/junit/platform/commons/support/ReflectionSupportTests.java +++ b/platform-tests/src/test/java/org/junit/platform/commons/support/ReflectionSupportTests.java @@ -13,11 +13,12 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.platform.commons.support.ReflectionSupport.toSupportResourcesList; import static org.junit.platform.commons.support.ReflectionSupport.toSupportResourcesStream; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotNullFor; import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotNullOrBlankFor; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotNullOrEmptyFor; import static org.junit.platform.commons.util.ClassLoaderUtils.getDefaultClassLoader; import java.lang.reflect.Field; @@ -31,7 +32,6 @@ import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestFactory; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.commons.io.ResourceFilter; import org.junit.platform.commons.util.ReflectionUtils; @@ -298,9 +298,8 @@ void findAllClassesInModuleDelegates() { @SuppressWarnings("DataFlowIssue") @Test void findAllClassesInModulePreconditions() { - var exception = assertThrows(PreconditionViolationException.class, + assertPreconditionViolationNotNullOrEmptyFor("Module name", () -> ReflectionSupport.findAllClassesInModule(null, allTypes, allNames)); - assertEquals("Module name must not be null or empty", exception.getMessage()); assertPreconditionViolationNotNullFor("class predicate", () -> ReflectionSupport.findAllClassesInModule("org.junit.platform.commons", null, allNames)); assertPreconditionViolationNotNullFor("name predicate", @@ -324,9 +323,8 @@ void findAllResourcesInModuleDelegates() { @SuppressWarnings({ "DataFlowIssue", "removal" }) @Test void findAllResourcesInModulePreconditions() { - var exception = assertThrows(PreconditionViolationException.class, + assertPreconditionViolationNotNullOrEmptyFor("Module name", () -> ReflectionSupport.findAllResourcesInModule(null, allResources)); - assertEquals("Module name must not be null or empty", exception.getMessage()); assertPreconditionViolationNotNullFor("resourceFilter", () -> ReflectionSupport.findAllResourcesInModule("org.junit.platform.commons", null)); } @@ -349,9 +347,8 @@ void streamAllResourcesInModuleDelegates() { @SuppressWarnings({ "DataFlowIssue", "removal" }) @Test void streamAllResourcesInModulePreconditions() { - var exception = assertThrows(PreconditionViolationException.class, + assertPreconditionViolationNotNullOrEmptyFor("Module name", () -> ReflectionSupport.streamAllResourcesInModule(null, allResources)); - assertEquals("Module name must not be null or empty", exception.getMessage()); assertPreconditionViolationNotNullFor("resourceFilter", () -> ReflectionSupport.streamAllResourcesInModule("org.junit.platform.commons", null)); } @@ -385,10 +382,8 @@ void invokeMethodPreconditions() throws Exception { assertPreconditionViolationNotNullFor("Method", () -> ReflectionSupport.invokeMethod(null, null, "true")); var method = Boolean.class.getMethod("toString"); - var exception = assertThrows(PreconditionViolationException.class, - () -> ReflectionSupport.invokeMethod(method, null)); - assertEquals("Cannot invoke non-static method [" + method.toGenericString() + "] on a null target.", - exception.getMessage()); + assertPreconditionViolationFor(() -> ReflectionSupport.invokeMethod(method, null)).withMessage( + "Cannot invoke non-static method [" + method.toGenericString() + "] on a null target."); } @Test @@ -435,11 +430,9 @@ void tryToReadFieldValuePreconditions() throws Exception { assertPreconditionViolationNotNullFor("Field", () -> ReflectionSupport.tryToReadFieldValue(null, this)); var instanceField = getClass().getDeclaredField("instanceField"); - Exception exception = assertThrows(PreconditionViolationException.class, - () -> ReflectionSupport.tryToReadFieldValue(instanceField, null)); - assertThat(exception)// - .hasMessageStartingWith("Cannot read non-static field")// - .hasMessageEndingWith("on a null instance."); + assertPreconditionViolationFor( + () -> ReflectionSupport.tryToReadFieldValue(instanceField, null)).withMessageStartingWith( + "Cannot read non-static field").withMessageEndingWith("on a null instance."); } @Test diff --git a/platform-tests/src/test/java/org/junit/platform/commons/support/ResourceSupportTests.java b/platform-tests/src/test/java/org/junit/platform/commons/support/ResourceSupportTests.java index 9797f28d58b1..0cc207eab838 100644 --- a/platform-tests/src/test/java/org/junit/platform/commons/support/ResourceSupportTests.java +++ b/platform-tests/src/test/java/org/junit/platform/commons/support/ResourceSupportTests.java @@ -13,9 +13,9 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotNullFor; import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotNullOrBlankFor; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotNullOrEmptyFor; import static org.junit.platform.commons.util.ClassLoaderUtils.getDefaultClassLoader; import java.net.URI; @@ -26,7 +26,6 @@ import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestFactory; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.commons.io.ResourceFilter; import org.junit.platform.commons.util.ReflectionUtils; @@ -185,9 +184,8 @@ void findAllResourcesInModuleDelegates() { @SuppressWarnings("DataFlowIssue") @Test void findAllResourcesInModulePreconditions() { - var exception = assertThrows(PreconditionViolationException.class, + assertPreconditionViolationNotNullOrEmptyFor("Module name", () -> ResourceSupport.findAllResourcesInModule(null, allResources)); - assertEquals("Module name must not be null or empty", exception.getMessage()); assertPreconditionViolationNotNullFor("Resource filter", () -> ResourceSupport.findAllResourcesInModule("org.junit.platform.commons", null)); } @@ -207,9 +205,8 @@ void streamAllResourcesInModuleDelegates() { @SuppressWarnings("DataFlowIssue") @Test void streamAllResourcesInModulePreconditions() { - var exception = assertThrows(PreconditionViolationException.class, + assertPreconditionViolationNotNullOrEmptyFor("Module name", () -> ResourceSupport.streamAllResourcesInModule(null, allResources)); - assertEquals("Module name must not be null or empty", exception.getMessage()); assertPreconditionViolationNotNullFor("Resource filter", () -> ResourceSupport.streamAllResourcesInModule("org.junit.platform.commons", null)); } diff --git a/platform-tests/src/test/java/org/junit/platform/commons/util/AnnotationUtilsTests.java b/platform-tests/src/test/java/org/junit/platform/commons/util/AnnotationUtilsTests.java index 4f7d0541cbd9..ff65811aeaf3 100644 --- a/platform-tests/src/test/java/org/junit/platform/commons/util/AnnotationUtilsTests.java +++ b/platform-tests/src/test/java/org/junit/platform/commons/util/AnnotationUtilsTests.java @@ -15,8 +15,8 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertIterableEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import static org.junit.platform.commons.util.AnnotationUtils.findAnnotatedFields; import static org.junit.platform.commons.util.AnnotationUtils.findAnnotatedMethods; import static org.junit.platform.commons.util.AnnotationUtils.findAnnotation; @@ -45,7 +45,6 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.commons.util.pkg1.ClassLevelDir; import org.junit.platform.commons.util.pkg1.InstanceLevelDir; import org.junit.platform.commons.util.pkg1.SuperclassWithStaticPackagePrivateBeforeMethod; @@ -210,10 +209,8 @@ void isAnnotatedWhenMetaPresentOnMethod() throws Exception { @Test void findRepeatableAnnotationsForNotRepeatableAnnotation() { - var exception = assertThrows(PreconditionViolationException.class, - () -> findRepeatableAnnotations(getClass(), Inherited.class)); - - assertThat(exception.getMessage()).isEqualTo(Inherited.class.getName() + " must be @Repeatable"); + assertPreconditionViolationFor(() -> findRepeatableAnnotations(getClass(), Inherited.class)).withMessage( + Inherited.class.getName() + " must be @Repeatable"); } @Test @@ -338,15 +335,13 @@ private void assertExtensionsFound(Class clazz, String... tags) { @SuppressWarnings("DataFlowIssue") @Test void findAnnotatedMethodsForNullClass() { - assertThrows(PreconditionViolationException.class, - () -> findAnnotatedMethods(null, Annotation1.class, TOP_DOWN)); + assertPreconditionViolationFor(() -> findAnnotatedMethods(null, Annotation1.class, TOP_DOWN)); } @SuppressWarnings("DataFlowIssue") @Test void findAnnotatedMethodsForNullAnnotationType() { - assertThrows(PreconditionViolationException.class, - () -> findAnnotatedMethods(ClassWithAnnotatedMethods.class, null, TOP_DOWN)); + assertPreconditionViolationFor(() -> findAnnotatedMethods(ClassWithAnnotatedMethods.class, null, TOP_DOWN)); } @Test @@ -426,21 +421,20 @@ void findAnnotatedMethodsForAnnotationUsedInInterface() throws Exception { @SuppressWarnings("DataFlowIssue") @Test void findAnnotatedFieldsForNullClass() { - assertThrows(PreconditionViolationException.class, - () -> findAnnotatedFields(null, Annotation1.class, isStringField, TOP_DOWN)); + assertPreconditionViolationFor(() -> findAnnotatedFields(null, Annotation1.class, isStringField, TOP_DOWN)); } @SuppressWarnings("DataFlowIssue") @Test void findAnnotatedFieldsForNullAnnotationType() { - assertThrows(PreconditionViolationException.class, + assertPreconditionViolationFor( () -> findAnnotatedFields(ClassWithAnnotatedFields.class, null, isStringField, TOP_DOWN)); } @SuppressWarnings("DataFlowIssue") @Test void findAnnotatedFieldsForNullPredicate() { - assertThrows(PreconditionViolationException.class, + assertPreconditionViolationFor( () -> findAnnotatedFields(ClassWithAnnotatedFields.class, Annotation1.class, null, TOP_DOWN)); } @@ -537,22 +531,19 @@ void findAnnotatedFieldsDoesNotAllowInstanceFieldToHideStaticField() throws Exce @SuppressWarnings("DataFlowIssue") @Test void findPublicAnnotatedFieldsForNullClass() { - assertThrows(PreconditionViolationException.class, - () -> findPublicAnnotatedFields(null, String.class, Annotation1.class)); + assertPreconditionViolationFor(() -> findPublicAnnotatedFields(null, String.class, Annotation1.class)); } @SuppressWarnings("DataFlowIssue") @Test void findPublicAnnotatedFieldsForNullFieldType() { - assertThrows(PreconditionViolationException.class, - () -> findPublicAnnotatedFields(getClass(), null, Annotation1.class)); + assertPreconditionViolationFor(() -> findPublicAnnotatedFields(getClass(), null, Annotation1.class)); } @SuppressWarnings("DataFlowIssue") @Test void findPublicAnnotatedFieldsForNullAnnotationType() { - assertThrows(PreconditionViolationException.class, - () -> findPublicAnnotatedFields(getClass(), String.class, null)); + assertPreconditionViolationFor(() -> findPublicAnnotatedFields(getClass(), String.class, null)); } @Test diff --git a/platform-tests/src/test/java/org/junit/platform/commons/util/ClassLoaderUtilsTests.java b/platform-tests/src/test/java/org/junit/platform/commons/util/ClassLoaderUtilsTests.java index ff550b9c11e6..3b0b4a21d224 100644 --- a/platform-tests/src/test/java/org/junit/platform/commons/util/ClassLoaderUtilsTests.java +++ b/platform-tests/src/test/java/org/junit/platform/commons/util/ClassLoaderUtilsTests.java @@ -11,15 +11,12 @@ package org.junit.platform.commons.util; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotNullFor; import static org.mockito.Mockito.mock; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.commons.test.TestClassLoader; /** @@ -32,8 +29,7 @@ class ClassLoaderUtilsTests { @SuppressWarnings("DataFlowIssue") @Test void getClassLoaderPreconditions() { - assertPreconditionViolationFor(() -> ClassLoaderUtils.getClassLoader(null))// - .withMessage("Class must not be null"); + assertPreconditionViolationNotNullFor("Class", () -> ClassLoaderUtils.getClassLoader(null)); } @Test @@ -103,8 +99,7 @@ void getDefaultClassLoaderWithNullContextClassLoader() { @SuppressWarnings("DataFlowIssue") @Test void getLocationFromNullFails() { - var exception = assertThrows(PreconditionViolationException.class, () -> ClassLoaderUtils.getLocation(null)); - assertEquals("object must not be null", exception.getMessage()); + assertPreconditionViolationNotNullFor("object", () -> ClassLoaderUtils.getLocation(null)); } @Test diff --git a/platform-tests/src/test/java/org/junit/platform/commons/util/CollectionUtilsTests.java b/platform-tests/src/test/java/org/junit/platform/commons/util/CollectionUtilsTests.java index c89768914341..d2fcedc2dd66 100644 --- a/platform-tests/src/test/java/org/junit/platform/commons/util/CollectionUtilsTests.java +++ b/platform-tests/src/test/java/org/junit/platform/commons/util/CollectionUtilsTests.java @@ -13,9 +13,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.DynamicTest.dynamicTest; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotNullFor; import java.lang.reflect.Array; import java.util.ArrayList; @@ -45,7 +46,6 @@ import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; -import org.junit.platform.commons.PreconditionViolationException; /** * Unit tests for {@link CollectionUtils}. @@ -60,16 +60,13 @@ class OnlyElement { @SuppressWarnings("DataFlowIssue") @Test void nullCollection() { - var exception = assertThrows(PreconditionViolationException.class, - () -> CollectionUtils.getOnlyElement(null)); - assertEquals("collection must not be null", exception.getMessage()); + assertPreconditionViolationNotNullFor("collection", () -> CollectionUtils.getOnlyElement(null)); } @Test void emptyCollection() { - var exception = assertThrows(PreconditionViolationException.class, - () -> CollectionUtils.getOnlyElement(Set.of())); - assertEquals("collection must contain exactly one element: []", exception.getMessage()); + assertPreconditionViolationFor(() -> CollectionUtils.getOnlyElement(Set.of())).withMessage( + "collection must contain exactly one element: []"); } @Test @@ -81,9 +78,8 @@ void singleElementCollection() { @Test void multiElementCollection() { - var exception = assertThrows(PreconditionViolationException.class, - () -> CollectionUtils.getOnlyElement(List.of("foo", "bar"))); - assertEquals("collection must contain exactly one element: [foo, bar]", exception.getMessage()); + assertPreconditionViolationFor(() -> CollectionUtils.getOnlyElement(List.of("foo", "bar"))).withMessage( + "collection must contain exactly one element: [foo, bar]"); } } @@ -93,9 +89,7 @@ class FirstElement { @SuppressWarnings("DataFlowIssue") @Test void nullCollection() { - var exception = assertThrows(PreconditionViolationException.class, - () -> CollectionUtils.getFirstElement(null)); - assertEquals("collection must not be null", exception.getMessage()); + assertPreconditionViolationNotNullFor("collection", () -> CollectionUtils.getFirstElement(null)); } @Test @@ -186,18 +180,13 @@ void isConvertibleToStreamForNull() { @SuppressWarnings("DataFlowIssue") @Test void toStreamWithNull() { - Exception exception = assertThrows(PreconditionViolationException.class, - () -> CollectionUtils.toStream(null)); - - assertThat(exception).hasMessage("Object must not be null"); + assertPreconditionViolationNotNullFor("Object", () -> CollectionUtils.toStream(null)); } @Test void toStreamWithUnsupportedObjectType() { - Exception exception = assertThrows(PreconditionViolationException.class, - () -> CollectionUtils.toStream("unknown")); - - assertThat(exception).hasMessage("Cannot convert instance of java.lang.String into a Stream: unknown"); + assertPreconditionViolationFor(() -> CollectionUtils.toStream("unknown")).withMessage( + "Cannot convert instance of java.lang.String into a Stream: unknown"); } @Test @@ -292,10 +281,9 @@ void toStreamWithIteratorProvider() { @Test void throwWhenIteratorNamedMethodDoesNotReturnAnIterator() { var o = new UnusableIteratorProvider("Test"); - var e = assertThrows(PreconditionViolationException.class, () -> CollectionUtils.toStream(o)); - - assertEquals("Cannot convert instance of %s into a Stream: %s".formatted( - UnusableIteratorProvider.class.getName(), o), e.getMessage()); + assertPreconditionViolationFor(() -> CollectionUtils.toStream(o)).withMessage( + "Cannot convert instance of %s into a Stream: %s".formatted(UnusableIteratorProvider.class.getName(), + o)); } @Test diff --git a/platform-tests/src/test/java/org/junit/platform/commons/util/DefaultClasspathScannerTests.java b/platform-tests/src/test/java/org/junit/platform/commons/util/DefaultClasspathScannerTests.java index b2dad7b0cf0e..4879a5db2d72 100644 --- a/platform-tests/src/test/java/org/junit/platform/commons/util/DefaultClasspathScannerTests.java +++ b/platform-tests/src/test/java/org/junit/platform/commons/util/DefaultClasspathScannerTests.java @@ -18,6 +18,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeFalse; import static org.junit.platform.commons.test.ConcurrencyTestingUtils.executeConcurrently; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import java.io.IOException; import java.io.InputStream; @@ -45,7 +46,6 @@ import org.junit.jupiter.api.extension.DisabledInEclipse; import org.junit.jupiter.api.fixtures.TrackLogRecords; import org.junit.jupiter.api.io.TempDir; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.commons.function.Try; import org.junit.platform.commons.io.Resource; import org.junit.platform.commons.io.ResourceFilter; @@ -445,33 +445,29 @@ void resourcesCanBeRead() throws IOException { @SuppressWarnings("DataFlowIssue") @Test void scanForClassesInPackageForNullBasePackage() { - assertThrows(PreconditionViolationException.class, - () -> classpathScanner.scanForClassesInPackage(null, allClasses)); + assertPreconditionViolationFor(() -> classpathScanner.scanForClassesInPackage(null, allClasses)); } @SuppressWarnings("DataFlowIssue") @Test void scanForResourcesInPackageForNullBasePackage() { - assertThrows(PreconditionViolationException.class, - () -> classpathScanner.scanForResourcesInPackage(null, allResources)); + assertPreconditionViolationFor(() -> classpathScanner.scanForResourcesInPackage(null, allResources)); } @Test void scanForClassesInPackageForWhitespaceBasePackage() { - assertThrows(PreconditionViolationException.class, - () -> classpathScanner.scanForClassesInPackage(" ", allClasses)); + assertPreconditionViolationFor(() -> classpathScanner.scanForClassesInPackage(" ", allClasses)); } @Test void scanForResourcesInPackageForWhitespaceBasePackage() { - assertThrows(PreconditionViolationException.class, - () -> classpathScanner.scanForResourcesInPackage(" ", allResources)); + assertPreconditionViolationFor(() -> classpathScanner.scanForResourcesInPackage(" ", allResources)); } @SuppressWarnings("DataFlowIssue") @Test void scanForClassesInPackageForNullClassFilter() { - assertThrows(PreconditionViolationException.class, + assertPreconditionViolationFor( () -> classpathScanner.scanForClassesInPackage("org.junit.platform.commons", null)); } @@ -555,20 +551,19 @@ void findAllClassesInClasspathRootWithFilter() throws Exception { @SuppressWarnings("DataFlowIssue") @Test void findAllClassesInClasspathRootForNullRoot() { - assertThrows(PreconditionViolationException.class, - () -> classpathScanner.scanForClassesInClasspathRoot(null, allClasses)); + assertPreconditionViolationFor(() -> classpathScanner.scanForClassesInClasspathRoot(null, allClasses)); } @Test void findAllClassesInClasspathRootForNonExistingRoot() { - assertThrows(PreconditionViolationException.class, + assertPreconditionViolationFor( () -> classpathScanner.scanForClassesInClasspathRoot(Path.of("does_not_exist").toUri(), allClasses)); } @SuppressWarnings("DataFlowIssue") @Test void findAllClassesInClasspathRootForNullClassFilter() { - assertThrows(PreconditionViolationException.class, + assertPreconditionViolationFor( () -> classpathScanner.scanForClassesInClasspathRoot(getTestClasspathRoot(), null)); } diff --git a/platform-tests/src/test/java/org/junit/platform/commons/util/ExceptionUtilsTests.java b/platform-tests/src/test/java/org/junit/platform/commons/util/ExceptionUtilsTests.java index c3d38f12864a..ef82870c3a58 100644 --- a/platform-tests/src/test/java/org/junit/platform/commons/util/ExceptionUtilsTests.java +++ b/platform-tests/src/test/java/org/junit/platform/commons/util/ExceptionUtilsTests.java @@ -12,6 +12,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import static org.junit.platform.commons.util.ExceptionUtils.findNestedThrowables; import static org.junit.platform.commons.util.ExceptionUtils.pruneStackTrace; import static org.junit.platform.commons.util.ExceptionUtils.readStackTrace; @@ -24,7 +25,6 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.junit.platform.commons.JUnitException; -import org.junit.platform.commons.PreconditionViolationException; /** * Unit tests for {@link ExceptionUtils}. @@ -37,7 +37,7 @@ class ExceptionUtilsTests { @SuppressWarnings("DataFlowIssue") @Test void throwAsUncheckedExceptionWithNullException() { - assertThrows(PreconditionViolationException.class, () -> throwAsUncheckedException(null)); + assertPreconditionViolationFor(() -> throwAsUncheckedException(null)); } @Test @@ -53,7 +53,7 @@ void throwAsUncheckedExceptionWithUncheckedException() { @SuppressWarnings("DataFlowIssue") @Test void readStackTraceForNullThrowable() { - assertThrows(PreconditionViolationException.class, () -> readStackTrace(null)); + assertPreconditionViolationFor(() -> readStackTrace(null)); } @Test diff --git a/platform-tests/src/test/java/org/junit/platform/commons/util/FunctionUtilsTests.java b/platform-tests/src/test/java/org/junit/platform/commons/util/FunctionUtilsTests.java index 6efdbb7a69f5..4de54efd023d 100644 --- a/platform-tests/src/test/java/org/junit/platform/commons/util/FunctionUtilsTests.java +++ b/platform-tests/src/test/java/org/junit/platform/commons/util/FunctionUtilsTests.java @@ -11,13 +11,11 @@ package org.junit.platform.commons.util; import static java.util.function.Predicate.isEqual; -import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotNullFor; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; /** * Unit tests for {@link FunctionUtils}. @@ -29,15 +27,13 @@ class FunctionUtilsTests { @SuppressWarnings("DataFlowIssue") @Test void whereWithNullFunction() { - var exception = assertThrows(PreconditionViolationException.class, () -> FunctionUtils.where(null, o -> true)); - assertEquals("function must not be null", exception.getMessage()); + assertPreconditionViolationNotNullFor("function", () -> FunctionUtils.where(null, o -> true)); } @SuppressWarnings("DataFlowIssue") @Test void whereWithNullPredicate() { - var exception = assertThrows(PreconditionViolationException.class, () -> FunctionUtils.where(o -> o, null)); - assertEquals("predicate must not be null", exception.getMessage()); + assertPreconditionViolationNotNullFor("predicate", () -> FunctionUtils.where(o -> o, null)); } @Test diff --git a/platform-tests/src/test/java/org/junit/platform/commons/util/PackageUtilsTests.java b/platform-tests/src/test/java/org/junit/platform/commons/util/PackageUtilsTests.java index 3f4ed0700d12..e6e853eb77b3 100644 --- a/platform-tests/src/test/java/org/junit/platform/commons/util/PackageUtilsTests.java +++ b/platform-tests/src/test/java/org/junit/platform/commons/util/PackageUtilsTests.java @@ -10,11 +10,11 @@ package org.junit.platform.commons.util; -import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.DynamicTest.dynamicTest; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotBlankFor; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotNullFor; import java.util.List; import java.util.function.Function; @@ -23,7 +23,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestFactory; import org.junit.jupiter.api.function.Executable; -import org.junit.platform.commons.PreconditionViolationException; import org.opentest4j.ValueWrapper; /** @@ -36,17 +35,14 @@ class PackageUtilsTests { @SuppressWarnings("DataFlowIssue") @Test void getAttributeWithNullType() { - var exception = assertThrows(PreconditionViolationException.class, - () -> PackageUtils.getAttribute(null, p -> "any")); - assertEquals("type must not be null", exception.getMessage()); + assertPreconditionViolationNotNullFor("type", () -> PackageUtils.getAttribute(null, p -> "any")); } @SuppressWarnings("DataFlowIssue") @Test void getAttributeWithNullFunction() { - var exception = assertThrows(PreconditionViolationException.class, + assertPreconditionViolationNotNullFor("function", () -> PackageUtils.getAttribute(getClass(), (Function) null)); - assertEquals("function must not be null", exception.getMessage()); } @SuppressWarnings("DataFlowIssue") @@ -81,23 +77,17 @@ private Executable isPresent(Function function) { @SuppressWarnings("DataFlowIssue") @Test void getAttributeWithNullTypeAndName() { - var exception = assertThrows(PreconditionViolationException.class, - () -> PackageUtils.getAttribute(null, "foo")); - assertEquals("type must not be null", exception.getMessage()); + assertPreconditionViolationNotNullFor("type", () -> PackageUtils.getAttribute(null, "foo")); } @SuppressWarnings("DataFlowIssue") @Test void getAttributeWithNullName() { - var exception = assertThrows(PreconditionViolationException.class, - () -> PackageUtils.getAttribute(getClass(), (String) null)); - assertEquals("name must not be blank", exception.getMessage()); + assertPreconditionViolationNotBlankFor("name", () -> PackageUtils.getAttribute(getClass(), (String) null)); } @Test void getAttributeWithEmptyName() { - var exception = assertThrows(PreconditionViolationException.class, - () -> PackageUtils.getAttribute(getClass(), "")); - assertEquals("name must not be blank", exception.getMessage()); + assertPreconditionViolationNotBlankFor("name", () -> PackageUtils.getAttribute(getClass(), "")); } } diff --git a/platform-tests/src/test/java/org/junit/platform/commons/util/PreconditionsTests.java b/platform-tests/src/test/java/org/junit/platform/commons/util/PreconditionsTests.java index 73e35ff00ee9..b9794960fc8e 100644 --- a/platform-tests/src/test/java/org/junit/platform/commons/util/PreconditionsTests.java +++ b/platform-tests/src/test/java/org/junit/platform/commons/util/PreconditionsTests.java @@ -11,9 +11,8 @@ package org.junit.platform.commons.util; import static java.util.Collections.singletonList; -import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import static org.junit.platform.commons.util.Preconditions.condition; import static org.junit.platform.commons.util.Preconditions.containsNoNullElements; import static org.junit.platform.commons.util.Preconditions.notBlank; @@ -24,7 +23,6 @@ import java.util.List; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; /** * Unit tests for {@link Preconditions}. @@ -44,9 +42,7 @@ void notNullPassesForNonNullObject() { void notNullThrowsForNullObject() { var message = "argument is null"; - var exception = assertThrows(PreconditionViolationException.class, () -> notNull(null, message)); - - assertEquals(message, exception.getMessage()); + assertPreconditionViolationFor(() -> notNull(null, message)).withMessage(message); } @Test @@ -54,9 +50,7 @@ void notNullThrowsForNullObjectAndMessageSupplier() { var message = "argument is null"; Object object = null; - var exception = assertThrows(PreconditionViolationException.class, () -> notNull(object, () -> message)); - - assertEquals(message, exception.getMessage()); + assertPreconditionViolationFor(() -> notNull(object, () -> message)).withMessage(message); } @Test @@ -87,37 +81,28 @@ void notEmptyPassesForCollectionWithNullElements() { void notEmptyThrowsForNullArray() { var message = "array is empty"; - var exception = assertThrows(PreconditionViolationException.class, () -> notEmpty((Object[]) null, message)); - - assertEquals(message, exception.getMessage()); + assertPreconditionViolationFor(() -> notEmpty((Object[]) null, message)).withMessage(message); } @Test void notEmptyThrowsForNullCollection() { var message = "collection is empty"; - var exception = assertThrows(PreconditionViolationException.class, - () -> notEmpty((Collection) null, message)); - - assertEquals(message, exception.getMessage()); + assertPreconditionViolationFor(() -> notEmpty((Collection) null, message)).withMessage(message); } @Test void notEmptyThrowsForEmptyArray() { var message = "array is empty"; - var exception = assertThrows(PreconditionViolationException.class, () -> notEmpty(new Object[0], message)); - - assertEquals(message, exception.getMessage()); + assertPreconditionViolationFor(() -> notEmpty(new Object[0], message)).withMessage(message); } @Test void notEmptyThrowsForEmptyCollection() { var message = "collection is empty"; - var exception = assertThrows(PreconditionViolationException.class, () -> notEmpty(List.of(), message)); - - assertEquals(message, exception.getMessage()); + assertPreconditionViolationFor(() -> notEmpty(List.of(), message)).withMessage(message); } @Test @@ -160,20 +145,14 @@ void containsNoNullElementsThrowsForArrayContainingNullElements() { var message = "array contains null elements"; Object[] array = { new Object(), null, new Object() }; - var exception = assertThrows(PreconditionViolationException.class, - () -> containsNoNullElements(array, message)); - - assertEquals(message, exception.getMessage()); + assertPreconditionViolationFor(() -> containsNoNullElements(array, message)).withMessage(message); } @Test void containsNoNullElementsThrowsForCollectionContainingNullElements() { var message = "collection contains null elements"; - var exception = assertThrows(PreconditionViolationException.class, - () -> containsNoNullElements(singletonList(null), message)); - - assertEquals(message, exception.getMessage()); + assertPreconditionViolationFor(() -> containsNoNullElements(singletonList(null), message)).withMessage(message); } @Test @@ -187,54 +166,42 @@ void notBlankPassesForNonBlankString() { void notBlankThrowsForNullString() { var message = "string shouldn't be blank"; - var exception = assertThrows(PreconditionViolationException.class, () -> notBlank(null, message)); - - assertEquals(message, exception.getMessage()); + assertPreconditionViolationFor(() -> notBlank(null, message)).withMessage(message); } @Test void notBlankThrowsForNullStringWithMessageSupplier() { var message = "string shouldn't be blank"; - var exception = assertThrows(PreconditionViolationException.class, () -> notBlank(null, () -> message)); - - assertEquals(message, exception.getMessage()); + assertPreconditionViolationFor(() -> notBlank(null, () -> message)).withMessage(message); } @Test void notBlankThrowsForEmptyString() { var message = "string shouldn't be blank"; - var exception = assertThrows(PreconditionViolationException.class, () -> notBlank("", message)); - - assertEquals(message, exception.getMessage()); + assertPreconditionViolationFor(() -> notBlank("", message)).withMessage(message); } @Test void notBlankThrowsForEmptyStringWithMessageSupplier() { var message = "string shouldn't be blank"; - var exception = assertThrows(PreconditionViolationException.class, () -> notBlank("", () -> message)); - - assertEquals(message, exception.getMessage()); + assertPreconditionViolationFor(() -> notBlank("", () -> message)).withMessage(message); } @Test void notBlankThrowsForBlankString() { var message = "string shouldn't be blank"; - var exception = assertThrows(PreconditionViolationException.class, () -> notBlank(" ", message)); - - assertEquals(message, exception.getMessage()); + assertPreconditionViolationFor(() -> notBlank(" ", message)).withMessage(message); } @Test void notBlankThrowsForBlankStringWithMessageSupplier() { var message = "string shouldn't be blank"; - var exception = assertThrows(PreconditionViolationException.class, () -> notBlank(" ", () -> message)); - - assertEquals(message, exception.getMessage()); + assertPreconditionViolationFor(() -> notBlank(" ", () -> message)).withMessage(message); } @Test @@ -251,18 +218,14 @@ void conditionPassesForTruePredicateWithMessageSupplier() { void conditionThrowsForFalsePredicate() { var message = "condition does not hold"; - var exception = assertThrows(PreconditionViolationException.class, () -> condition(false, message)); - - assertEquals(message, exception.getMessage()); + assertPreconditionViolationFor(() -> condition(false, message)).withMessage(message); } @Test void conditionThrowsForFalsePredicateWithMessageSupplier() { var message = "condition does not hold"; - var exception = assertThrows(PreconditionViolationException.class, () -> condition(false, () -> message)); - - assertEquals(message, exception.getMessage()); + assertPreconditionViolationFor(() -> condition(false, () -> message)).withMessage(message); } } diff --git a/platform-tests/src/test/java/org/junit/platform/commons/util/ReflectionUtilsTests.java b/platform-tests/src/test/java/org/junit/platform/commons/util/ReflectionUtilsTests.java index ad89f877393e..a59585fd96d5 100644 --- a/platform-tests/src/test/java/org/junit/platform/commons/util/ReflectionUtilsTests.java +++ b/platform-tests/src/test/java/org/junit/platform/commons/util/ReflectionUtilsTests.java @@ -25,6 +25,8 @@ import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotNullFor; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotNullOrBlankFor; import static org.junit.platform.commons.util.ReflectionUtils.HierarchyTraversalMode.BOTTOM_UP; import static org.junit.platform.commons.util.ReflectionUtils.HierarchyTraversalMode.TOP_DOWN; import static org.junit.platform.commons.util.ReflectionUtils.findFields; @@ -68,7 +70,6 @@ import org.junit.jupiter.api.fixtures.TrackLogRecords; import org.junit.jupiter.api.io.TempDir; import org.junit.platform.commons.JUnitException; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.commons.io.Resource; import org.junit.platform.commons.logging.LogRecordListener; import org.junit.platform.commons.test.TestClassLoader; @@ -121,8 +122,7 @@ void returnsPrimitiveVoid() throws Exception { @SuppressWarnings("DataFlowIssue") @Test void getAllAssignmentCompatibleClassesWithNullClass() { - assertThrows(PreconditionViolationException.class, - () -> ReflectionUtils.getAllAssignmentCompatibleClasses(null)); + assertPreconditionViolationFor(() -> ReflectionUtils.getAllAssignmentCompatibleClasses(null)); } @Test @@ -140,10 +140,10 @@ void newInstance() { assertThat(ReflectionUtils.newInstance(C.class, "one", "two")).isNotNull(); assertThat(ReflectionUtils.newInstance(C.class)).isNotNull(); - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.newInstance(C.class, "one", null)); - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.newInstance(C.class, null, "two")); - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.newInstance(C.class, null, null)); - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.newInstance(C.class, ((Object[]) null))); + assertPreconditionViolationFor(() -> ReflectionUtils.newInstance(C.class, "one", null)); + assertPreconditionViolationFor(() -> ReflectionUtils.newInstance(C.class, null, "two")); + assertPreconditionViolationFor(() -> ReflectionUtils.newInstance(C.class, null, null)); + assertPreconditionViolationFor(() -> ReflectionUtils.newInstance(C.class, ((Object[]) null))); var exception = assertThrows(RuntimeException.class, () -> ReflectionUtils.newInstance(Exploder.class)); assertThat(exception).hasMessage("boom"); @@ -257,8 +257,8 @@ private static void createDirectories(Path... paths) throws IOException { @Test void getDeclaredConstructorPreconditions() { // @formatter:off - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.getDeclaredConstructor(null)); - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.getDeclaredConstructor(ClassWithTwoConstructors.class)); + assertPreconditionViolationFor(() -> ReflectionUtils.getDeclaredConstructor(null)); + assertPreconditionViolationFor(() -> ReflectionUtils.getDeclaredConstructor(ClassWithTwoConstructors.class)); // @formatter:on } @@ -555,8 +555,8 @@ class IsClassAssignableToClassTests { @SuppressWarnings("DataFlowIssue") @Test void isAssignableToForNullSourceType() { - assertPreconditionViolationFor(() -> ReflectionUtils.isAssignableTo(null, getClass()))// - .withMessage("source type must not be null"); + assertPreconditionViolationNotNullFor("source type", + () -> ReflectionUtils.isAssignableTo(null, getClass())); } @Test @@ -568,8 +568,8 @@ void isAssignableToForPrimitiveSourceType() { @SuppressWarnings("DataFlowIssue") @Test void isAssignableToForNullTargetType() { - assertPreconditionViolationFor(() -> ReflectionUtils.isAssignableTo(getClass(), null))// - .withMessage("target type must not be null"); + assertPreconditionViolationNotNullFor("target type", + () -> ReflectionUtils.isAssignableTo(getClass(), null)); } @Test @@ -624,8 +624,7 @@ class IsObjectAssignableToClassTests { @SuppressWarnings("DataFlowIssue") @Test void isAssignableToForNullClass() { - assertThrows(PreconditionViolationException.class, - () -> ReflectionUtils.isAssignableTo(new Object(), null)); + assertPreconditionViolationFor(() -> ReflectionUtils.isAssignableTo(new Object(), null)); } @Test @@ -691,8 +690,8 @@ class MethodInvocationTests { @Test void invokeMethodPreconditions() { // @formatter:off - assertThrows(PreconditionViolationException.class, () -> invokeMethod(null, new Object())); - assertThrows(PreconditionViolationException.class, () -> invokeMethod(Object.class.getMethod("hashCode"), null)); + assertPreconditionViolationFor(() -> invokeMethod(null, new Object())); + assertPreconditionViolationFor(() -> invokeMethod(Object.class.getMethod("hashCode"), null)); // @formatter:on } @@ -757,11 +756,11 @@ class ResourceLoadingTests { @SuppressWarnings("DataFlowIssue") @Test void tryToGetResourcePreconditions() { - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.tryToGetResources("")); - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.tryToGetResources(" ")); + assertPreconditionViolationFor(() -> ReflectionUtils.tryToGetResources("")); + assertPreconditionViolationFor(() -> ReflectionUtils.tryToGetResources(" ")); - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.tryToGetResources(null)); - assertThrows(PreconditionViolationException.class, + assertPreconditionViolationFor(() -> ReflectionUtils.tryToGetResources(null)); + assertPreconditionViolationFor( () -> ReflectionUtils.tryToGetResources("org/junit/platform/commons/example.resource", null)); } @@ -799,13 +798,12 @@ class ClassLoadingTests { @SuppressWarnings("DataFlowIssue") @Test void tryToLoadClassPreconditions() { - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.tryToLoadClass(null)); - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.tryToLoadClass("")); - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.tryToLoadClass(" ")); + assertPreconditionViolationFor(() -> ReflectionUtils.tryToLoadClass(null)); + assertPreconditionViolationFor(() -> ReflectionUtils.tryToLoadClass("")); + assertPreconditionViolationFor(() -> ReflectionUtils.tryToLoadClass(" ")); - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.tryToLoadClass(null, null)); - assertThrows(PreconditionViolationException.class, - () -> ReflectionUtils.tryToLoadClass(getClass().getName(), null)); + assertPreconditionViolationFor(() -> ReflectionUtils.tryToLoadClass(null, null)); + assertPreconditionViolationFor(() -> ReflectionUtils.tryToLoadClass(getClass().getName(), null)); } @Test @@ -967,9 +965,9 @@ class FullyQualifiedMethodNameTests { @Test void getFullyQualifiedMethodNamePreconditions() { // @formatter:off - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.getFullyQualifiedMethodName(null, null)); - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.getFullyQualifiedMethodName(null, "testMethod")); - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.getFullyQualifiedMethodName(Object.class, null)); + assertPreconditionViolationFor(() -> ReflectionUtils.getFullyQualifiedMethodName(null, null)); + assertPreconditionViolationFor(() -> ReflectionUtils.getFullyQualifiedMethodName(null, "testMethod")); + assertPreconditionViolationFor(() -> ReflectionUtils.getFullyQualifiedMethodName(Object.class, null)); // @formatter:on } @@ -1003,16 +1001,16 @@ void getFullyQualifiedMethodNameForMethodWithMultipleParameters() { @Test void parseFullyQualifiedMethodNamePreconditions() { // @formatter:off - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.parseFullyQualifiedMethodName(null)); - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.parseFullyQualifiedMethodName("")); - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.parseFullyQualifiedMethodName(" ")); - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.parseFullyQualifiedMethodName("java.lang.Object#")); - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.parseFullyQualifiedMethodName("#equals")); - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.parseFullyQualifiedMethodName("#")); - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.parseFullyQualifiedMethodName("java.lang.Object")); - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.parseFullyQualifiedMethodName("equals")); - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.parseFullyQualifiedMethodName("()")); - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.parseFullyQualifiedMethodName("(int, java.lang.Object)")); + assertPreconditionViolationFor(() -> ReflectionUtils.parseFullyQualifiedMethodName(null)); + assertPreconditionViolationFor(() -> ReflectionUtils.parseFullyQualifiedMethodName("")); + assertPreconditionViolationFor(() -> ReflectionUtils.parseFullyQualifiedMethodName(" ")); + assertPreconditionViolationFor(() -> ReflectionUtils.parseFullyQualifiedMethodName("java.lang.Object#")); + assertPreconditionViolationFor(() -> ReflectionUtils.parseFullyQualifiedMethodName("#equals")); + assertPreconditionViolationFor(() -> ReflectionUtils.parseFullyQualifiedMethodName("#")); + assertPreconditionViolationFor(() -> ReflectionUtils.parseFullyQualifiedMethodName("java.lang.Object")); + assertPreconditionViolationFor(() -> ReflectionUtils.parseFullyQualifiedMethodName("equals")); + assertPreconditionViolationFor(() -> ReflectionUtils.parseFullyQualifiedMethodName("()")); + assertPreconditionViolationFor(() -> ReflectionUtils.parseFullyQualifiedMethodName("(int, java.lang.Object)")); // @formatter:on } @@ -1043,9 +1041,9 @@ class NestedClassTests { @Test void findNestedClassesPreconditions() { // @formatter:off - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.findNestedClasses(null, null)); - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.findNestedClasses(null, clazz -> true)); - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.findNestedClasses(getClass(), null)); + assertPreconditionViolationFor(() -> ReflectionUtils.findNestedClasses(null, null)); + assertPreconditionViolationFor(() -> ReflectionUtils.findNestedClasses(null, clazz -> true)); + assertPreconditionViolationFor(() -> ReflectionUtils.findNestedClasses(getClass(), null)); // @formatter:on } @@ -1053,10 +1051,10 @@ void findNestedClassesPreconditions() { @Test void isNestedClassPresentPreconditions() { // @formatter:off - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.isNestedClassPresent(null, null, null)); - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.isNestedClassPresent(null, clazz -> true, CycleErrorHandling.THROW_EXCEPTION)); - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.isNestedClassPresent(getClass(), null, CycleErrorHandling.ABORT_VISIT)); - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.isNestedClassPresent(getClass(), clazz -> true, null)); + assertPreconditionViolationFor(() -> ReflectionUtils.isNestedClassPresent(null, null, null)); + assertPreconditionViolationFor(() -> ReflectionUtils.isNestedClassPresent(null, clazz -> true, CycleErrorHandling.THROW_EXCEPTION)); + assertPreconditionViolationFor(() -> ReflectionUtils.isNestedClassPresent(getClass(), null, CycleErrorHandling.ABORT_VISIT)); + assertPreconditionViolationFor(() -> ReflectionUtils.isNestedClassPresent(getClass(), clazz -> true, null)); // @formatter:on } @@ -1242,10 +1240,9 @@ class MethodUtilitiesTests { @SuppressWarnings("DataFlowIssue") @Test void tryToGetMethodPreconditions() { - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.tryToGetMethod(null, null)); - assertThrows(PreconditionViolationException.class, - () -> ReflectionUtils.tryToGetMethod(String.class, null)); - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.tryToGetMethod(null, "hashCode")); + assertPreconditionViolationFor(() -> ReflectionUtils.tryToGetMethod(null, null)); + assertPreconditionViolationFor(() -> ReflectionUtils.tryToGetMethod(String.class, null)); + assertPreconditionViolationFor(() -> ReflectionUtils.tryToGetMethod(null, "hashCode")); } @Test @@ -1267,8 +1264,8 @@ void tryToGetMethod() throws Exception { @SuppressWarnings("DataFlowIssue") @Test void isMethodPresentPreconditions() { - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.isMethodPresent(null, m -> true)); - assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.isMethodPresent(getClass(), null)); + assertPreconditionViolationFor(() -> ReflectionUtils.isMethodPresent(null, m -> true)); + assertPreconditionViolationFor(() -> ReflectionUtils.isMethodPresent(getClass(), null)); } @Test @@ -1290,23 +1287,21 @@ class FindMethodTests { @Test void findMethodByParameterTypesPreconditions() { // @formatter:off - assertThrows(PreconditionViolationException.class, () -> findMethod(null, null)); - assertThrows(PreconditionViolationException.class, () -> findMethod(null, "method")); + assertPreconditionViolationFor(() -> findMethod(null, null)); + assertPreconditionViolationFor(() -> findMethod(null, "method")); - RuntimeException exception = assertThrows(PreconditionViolationException.class, () -> findMethod(String.class, null)); - assertThat(exception).hasMessage("Method name must not be null or blank"); + assertPreconditionViolationNotNullOrBlankFor("Method name", () -> findMethod(String.class, null)); - exception = assertThrows(PreconditionViolationException.class, () -> findMethod(String.class, " ")); - assertThat(exception).hasMessage("Method name must not be null or blank"); + assertPreconditionViolationNotNullOrBlankFor("Method name", () -> findMethod(String.class, " ")); - exception = assertThrows(PreconditionViolationException.class, () -> findMethod(Files.class, "copy", (Class[]) null)); - assertThat(exception).hasMessage("Parameter types array must not be null"); + assertPreconditionViolationNotNullFor("Parameter types array",// + () -> findMethod(Files.class, "copy", (Class[]) null)); - exception = assertThrows(PreconditionViolationException.class, () -> findMethod(Files.class, "copy", (Class) null)); - assertThat(exception).hasMessage("Individual parameter types must not be null"); + assertPreconditionViolationNotNullFor("Individual parameter types",// + () -> findMethod(Files.class, "copy", (Class) null)); - exception = assertThrows(PreconditionViolationException.class, () -> findMethod(Files.class, "copy", new Class[] { Path.class, null })); - assertThat(exception).hasMessage("Individual parameter types must not be null"); + assertPreconditionViolationNotNullFor("Individual parameter types",// + () -> findMethod(Files.class, "copy", new Class[] { Path.class, null })); // @formatter:on } @@ -1479,14 +1474,14 @@ class FindMethodsTests { @Test void findMethodsPreconditions() { // @formatter:off - assertThrows(PreconditionViolationException.class, () -> findMethods(null, null)); - assertThrows(PreconditionViolationException.class, () -> findMethods(null, clazz -> true)); - assertThrows(PreconditionViolationException.class, () -> findMethods(String.class, null)); - - assertThrows(PreconditionViolationException.class, () -> findMethods(null, null, null)); - assertThrows(PreconditionViolationException.class, () -> findMethods(null, clazz -> true, BOTTOM_UP)); - assertThrows(PreconditionViolationException.class, () -> findMethods(String.class, null, BOTTOM_UP)); - assertThrows(PreconditionViolationException.class, () -> findMethods(String.class, clazz -> true, null)); + assertPreconditionViolationFor(() -> findMethods(null, null)); + assertPreconditionViolationFor(() -> findMethods(null, clazz -> true)); + assertPreconditionViolationFor(() -> findMethods(String.class, null)); + + assertPreconditionViolationFor(() -> findMethods(null, null, null)); + assertPreconditionViolationFor(() -> findMethods(null, clazz -> true, BOTTOM_UP)); + assertPreconditionViolationFor(() -> findMethods(String.class, null, BOTTOM_UP)); + assertPreconditionViolationFor(() -> findMethods(String.class, clazz -> true, null)); // @formatter:on } @@ -1915,11 +1910,8 @@ void tryToReadFieldValueOfExistingInstanceField() throws Exception { var field = MyClass.class.getDeclaredField("instanceField"); assertThat(tryToReadFieldValue(field, instance).getNonNull()).isEqualTo(42); - var exception = assertThrows(PreconditionViolationException.class, - () -> tryToReadFieldValue(field, null).get()); - assertThat(exception)// - .hasMessageStartingWith("Cannot read non-static field")// - .hasMessageEndingWith("on a null instance."); + assertPreconditionViolationFor(() -> tryToReadFieldValue(field, null).get()).withMessageStartingWith( + "Cannot read non-static field").withMessageEndingWith("on a null instance."); } } @@ -1953,9 +1945,9 @@ void findFieldsDoesNotAllowInstanceFieldToHideStaticField() throws Exception { @Test void readFieldValuesPreconditions() { List fields = new ArrayList<>(); - assertThrows(PreconditionViolationException.class, () -> readFieldValues(null, new Object())); - assertThrows(PreconditionViolationException.class, () -> readFieldValues(fields, null, null)); - assertThrows(PreconditionViolationException.class, () -> readFieldValues(fields, new Object(), null)); + assertPreconditionViolationFor(() -> readFieldValues(null, new Object())); + assertPreconditionViolationFor(() -> readFieldValues(fields, null, null)); + assertPreconditionViolationFor(() -> readFieldValues(fields, new Object(), null)); } @Test diff --git a/platform-tests/src/test/java/org/junit/platform/commons/util/StringUtilsTests.java b/platform-tests/src/test/java/org/junit/platform/commons/util/StringUtilsTests.java index 7881e831c151..e2f05db348b9 100644 --- a/platform-tests/src/test/java/org/junit/platform/commons/util/StringUtilsTests.java +++ b/platform-tests/src/test/java/org/junit/platform/commons/util/StringUtilsTests.java @@ -15,8 +15,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import static org.junit.platform.commons.util.StringUtils.containsIsoControlCharacter; import static org.junit.platform.commons.util.StringUtils.containsWhitespace; import static org.junit.platform.commons.util.StringUtils.doesNotContainIsoControlCharacter; @@ -29,7 +29,6 @@ import org.jspecify.annotations.NullUnmarked; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; /** * Unit tests for {@link StringUtils}. @@ -109,7 +108,7 @@ void replaceControlCharacters() { assertEquals("abc", replaceIsoControlCharacters("abc", "?")); assertEquals("...", replaceIsoControlCharacters("...", "?")); - assertThrows(PreconditionViolationException.class, () -> replaceIsoControlCharacters("", null)); + assertPreconditionViolationFor(() -> replaceIsoControlCharacters("", null)); } @SuppressWarnings("DataFlowIssue") @@ -126,7 +125,7 @@ void replaceWhitespaces() { assertEquals(" ", replaceWhitespaceCharacters("\u000B", " ")); assertEquals(" ", replaceWhitespaceCharacters("\f", " ")); - assertThrows(PreconditionViolationException.class, () -> replaceWhitespaceCharacters("", null)); + assertPreconditionViolationFor(() -> replaceWhitespaceCharacters("", null)); } @Test diff --git a/platform-tests/src/test/java/org/junit/platform/commons/util/ToStringBuilderTests.java b/platform-tests/src/test/java/org/junit/platform/commons/util/ToStringBuilderTests.java index ec4b984ddd4a..35fe1e6dbf96 100644 --- a/platform-tests/src/test/java/org/junit/platform/commons/util/ToStringBuilderTests.java +++ b/platform-tests/src/test/java/org/junit/platform/commons/util/ToStringBuilderTests.java @@ -11,14 +11,13 @@ package org.junit.platform.commons.util; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import java.util.LinkedHashMap; import java.util.Map; import org.jspecify.annotations.NullUnmarked; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; /** * Unit tests for {@link ToStringBuilder}. @@ -30,13 +29,13 @@ class ToStringBuilderTests { @SuppressWarnings("DataFlowIssue") @Test void withNullObject() { - assertThrows(PreconditionViolationException.class, () -> new ToStringBuilder((Object) null)); + assertPreconditionViolationFor(() -> new ToStringBuilder((Object) null)); } @SuppressWarnings("DataFlowIssue") @Test void withNullClass() { - assertThrows(PreconditionViolationException.class, () -> new ToStringBuilder((Class) null)); + assertPreconditionViolationFor(() -> new ToStringBuilder((Class) null)); } @SuppressWarnings("DataFlowIssue") @@ -44,9 +43,9 @@ void withNullClass() { void appendWithIllegalName() { var builder = new ToStringBuilder(""); - assertThrows(PreconditionViolationException.class, () -> builder.append(null, "")); - assertThrows(PreconditionViolationException.class, () -> builder.append("", "")); - assertThrows(PreconditionViolationException.class, () -> builder.append(" ", "")); + assertPreconditionViolationFor(() -> builder.append(null, "")); + assertPreconditionViolationFor(() -> builder.append("", "")); + assertPreconditionViolationFor(() -> builder.append(" ", "")); } @Test diff --git a/platform-tests/src/test/java/org/junit/platform/console/command/DiscoveryRequestCreatorTests.java b/platform-tests/src/test/java/org/junit/platform/console/command/DiscoveryRequestCreatorTests.java index 207e120048b2..5ef909fc57f0 100644 --- a/platform-tests/src/test/java/org/junit/platform/console/command/DiscoveryRequestCreatorTests.java +++ b/platform-tests/src/test/java/org/junit/platform/console/command/DiscoveryRequestCreatorTests.java @@ -13,7 +13,7 @@ import static java.util.stream.Collectors.toMap; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import static org.junit.platform.engine.discovery.ClassNameFilter.STANDARD_INCLUDE_PATTERN; import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass; import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClasspathResource; @@ -36,7 +36,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.fixtures.TrackLogRecords; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.commons.logging.LogRecordListener; import org.junit.platform.console.options.TestDiscoveryOptions; import org.junit.platform.engine.Filter; @@ -109,9 +108,7 @@ void doesNotSupportScanClasspathAndExplicitSelectors() { options.setScanClasspath(true); options.setSelectedClasses(List.of(selectClass("SomeTest"))); - Throwable cause = assertThrows(PreconditionViolationException.class, this::convert); - - assertThat(cause).hasMessageContaining("not supported"); + assertPreconditionViolationFor(this::convert).withMessageContaining("not supported"); } @Test diff --git a/platform-tests/src/test/java/org/junit/platform/engine/CompositeTestDescriptorVisitorTests.java b/platform-tests/src/test/java/org/junit/platform/engine/CompositeTestDescriptorVisitorTests.java index 1e6ff2924a7e..217922a19379 100644 --- a/platform-tests/src/test/java/org/junit/platform/engine/CompositeTestDescriptorVisitorTests.java +++ b/platform-tests/src/test/java/org/junit/platform/engine/CompositeTestDescriptorVisitorTests.java @@ -11,12 +11,11 @@ package org.junit.platform.engine; import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.engine.TestDescriptor.Visitor; import org.mockito.InOrder; @@ -25,9 +24,9 @@ class CompositeTestDescriptorVisitorTests { @SuppressWarnings("DataFlowIssue") @Test void checksPreconditions() { - assertThrows(PreconditionViolationException.class, Visitor::composite); - assertThrows(PreconditionViolationException.class, () -> Visitor.composite((Visitor[]) null)); - assertThrows(PreconditionViolationException.class, () -> Visitor.composite((Visitor) null)); + assertPreconditionViolationFor(Visitor::composite); + assertPreconditionViolationFor(() -> Visitor.composite((Visitor[]) null)); + assertPreconditionViolationFor(() -> Visitor.composite((Visitor) null)); } @Test diff --git a/platform-tests/src/test/java/org/junit/platform/engine/TestTagTests.java b/platform-tests/src/test/java/org/junit/platform/engine/TestTagTests.java index 70c1e4da3339..a87fc36cd479 100644 --- a/platform-tests/src/test/java/org/junit/platform/engine/TestTagTests.java +++ b/platform-tests/src/test/java/org/junit/platform/engine/TestTagTests.java @@ -10,16 +10,14 @@ package org.junit.platform.engine; -import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; /** * Unit tests for {@link TestTag}. @@ -99,9 +97,8 @@ private static void nope(String tag) { } private void assertSyntaxViolation(String tag) { - var exception = assertThrows(PreconditionViolationException.class, () -> TestTag.create(tag)); - assertThat(exception).hasMessageStartingWith("Tag name"); - assertThat(exception).hasMessageEndingWith("must be syntactically valid"); + assertPreconditionViolationFor(() -> TestTag.create(tag)).withMessageStartingWith( + "Tag name").withMessageEndingWith("must be syntactically valid"); } } diff --git a/platform-tests/src/test/java/org/junit/platform/engine/UniqueIdTests.java b/platform-tests/src/test/java/org/junit/platform/engine/UniqueIdTests.java index 5c1fb2b9f7bf..a033b03a8153 100644 --- a/platform-tests/src/test/java/org/junit/platform/engine/UniqueIdTests.java +++ b/platform-tests/src/test/java/org/junit/platform/engine/UniqueIdTests.java @@ -15,8 +15,8 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import java.util.Optional; @@ -24,7 +24,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.engine.UniqueId.Segment; /** @@ -128,9 +127,9 @@ void appendingSegmentInstance() { void appendingNullIsNotAllowed() { var uniqueId = UniqueId.forEngine(ENGINE_ID); - assertThrows(PreconditionViolationException.class, () -> uniqueId.append(null)); - assertThrows(PreconditionViolationException.class, () -> uniqueId.append(null, "foo")); - assertThrows(PreconditionViolationException.class, () -> uniqueId.append("foo", null)); + assertPreconditionViolationFor(() -> uniqueId.append(null)); + assertPreconditionViolationFor(() -> uniqueId.append(null, "foo")); + assertPreconditionViolationFor(() -> uniqueId.append("foo", null)); } } @@ -235,7 +234,7 @@ class Prefixing { void nullIsNotAPrefix() { var id = UniqueId.forEngine(ENGINE_ID); - assertThrows(PreconditionViolationException.class, () -> id.hasPrefix(null)); + assertPreconditionViolationFor(() -> id.hasPrefix(null)); } @Test @@ -285,7 +284,7 @@ void returnsLastSegment() { @Test void removesLastSegment() { var uniqueId = UniqueId.forEngine("foo"); - assertThrows(PreconditionViolationException.class, uniqueId::removeLastSegment); + assertPreconditionViolationFor(uniqueId::removeLastSegment); var newUniqueId = uniqueId.append("type", "bar").removeLastSegment(); assertEquals(uniqueId, newUniqueId); diff --git a/platform-tests/src/test/java/org/junit/platform/engine/discovery/ClassNameFilterTests.java b/platform-tests/src/test/java/org/junit/platform/engine/discovery/ClassNameFilterTests.java index 6abf2556458e..eb3d28d5ec5f 100644 --- a/platform-tests/src/test/java/org/junit/platform/engine/discovery/ClassNameFilterTests.java +++ b/platform-tests/src/test/java/org/junit/platform/engine/discovery/ClassNameFilterTests.java @@ -11,12 +11,12 @@ package org.junit.platform.engine.discovery; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotNullOrEmptyFor; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; /** * @since 1.0 @@ -26,15 +26,13 @@ class ClassNameFilterTests { @SuppressWarnings("DataFlowIssue") @Test void includeClassNamePatternsChecksPreconditions() { - assertThatThrownBy(() -> ClassNameFilter.includeClassNamePatterns((String[]) null)) // - .isInstanceOf(PreconditionViolationException.class) // - .hasMessage("patterns array must not be null or empty"); - assertThatThrownBy(() -> ClassNameFilter.includeClassNamePatterns(new String[0])) // - .isInstanceOf(PreconditionViolationException.class) // - .hasMessage("patterns array must not be null or empty"); - assertThatThrownBy(() -> ClassNameFilter.includeClassNamePatterns(new String[] { null })) // - .isInstanceOf(PreconditionViolationException.class) // - .hasMessage("patterns array must not contain null elements"); + assertPreconditionViolationNotNullOrEmptyFor("patterns array", + () -> ClassNameFilter.includeClassNamePatterns((String[]) null)); + assertPreconditionViolationNotNullOrEmptyFor("patterns array", + () -> ClassNameFilter.includeClassNamePatterns(new String[0])); + assertPreconditionViolationFor( + () -> ClassNameFilter.includeClassNamePatterns(new String[] { null })).withMessage( + "patterns array must not contain null elements"); } @Test @@ -89,15 +87,13 @@ void includeClassNamePatternsWithMultiplePatterns() { @SuppressWarnings("DataFlowIssue") @Test void excludeClassNamePatternsChecksPreconditions() { - assertThatThrownBy(() -> ClassNameFilter.excludeClassNamePatterns((String[]) null)) // - .isInstanceOf(PreconditionViolationException.class) // - .hasMessage("patterns array must not be null or empty"); - assertThatThrownBy(() -> ClassNameFilter.excludeClassNamePatterns(new String[0])) // - .isInstanceOf(PreconditionViolationException.class) // - .hasMessage("patterns array must not be null or empty"); - assertThatThrownBy(() -> ClassNameFilter.excludeClassNamePatterns(new String[] { null })) // - .isInstanceOf(PreconditionViolationException.class) // - .hasMessage("patterns array must not contain null elements"); + assertPreconditionViolationNotNullOrEmptyFor("patterns array", + () -> ClassNameFilter.excludeClassNamePatterns((String[]) null)); + assertPreconditionViolationNotNullOrEmptyFor("patterns array", + () -> ClassNameFilter.excludeClassNamePatterns(new String[0])); + assertPreconditionViolationFor( + () -> ClassNameFilter.excludeClassNamePatterns(new String[] { null })).withMessage( + "patterns array must not contain null elements"); } @Test diff --git a/platform-tests/src/test/java/org/junit/platform/engine/discovery/ClassSelectorTests.java b/platform-tests/src/test/java/org/junit/platform/engine/discovery/ClassSelectorTests.java index 80dd13652a1a..43c1761db775 100644 --- a/platform-tests/src/test/java/org/junit/platform/engine/discovery/ClassSelectorTests.java +++ b/platform-tests/src/test/java/org/junit/platform/engine/discovery/ClassSelectorTests.java @@ -11,11 +11,10 @@ package org.junit.platform.engine.discovery; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.EqualsAndHashCodeAssertions.assertEqualsAndHashCode; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; /** * Unit tests for {@link ClassSelector}. @@ -38,10 +37,8 @@ void equalsAndHashCode() { void preservesOriginalExceptionWhenTryingToLoadClass() { var selector = new ClassSelector(null, "org.example.TestClass"); - var e = assertThrows(PreconditionViolationException.class, selector::getJavaClass); - - assertThat(e).hasMessage("Could not load class with name: org.example.TestClass").hasCauseInstanceOf( - ClassNotFoundException.class); + assertPreconditionViolationFor(selector::getJavaClass).withMessage( + "Could not load class with name: org.example.TestClass").withCauseInstanceOf(ClassNotFoundException.class); } @Test diff --git a/platform-tests/src/test/java/org/junit/platform/engine/discovery/DiscoverySelectorsTests.java b/platform-tests/src/test/java/org/junit/platform/engine/discovery/DiscoverySelectorsTests.java index 164ee1d7e834..9576f163740f 100644 --- a/platform-tests/src/test/java/org/junit/platform/engine/discovery/DiscoverySelectorsTests.java +++ b/platform-tests/src/test/java/org/junit/platform/engine/discovery/DiscoverySelectorsTests.java @@ -16,9 +16,9 @@ import static org.assertj.core.api.InstanceOfAssertFactories.type; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.engine.discovery.JupiterUniqueIdBuilder.uniqueIdForMethod; import static org.junit.jupiter.params.provider.Arguments.arguments; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass; import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClasses; import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClassesByName; @@ -55,7 +55,6 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.commons.io.Resource; import org.junit.platform.commons.test.TestClassLoader; import org.junit.platform.commons.util.ReflectionUtils; @@ -738,8 +737,7 @@ void selectMethodByClassAndMethodPreconditions() { @MethodSource("invalidFullyQualifiedMethodNames") @DisplayName("Preconditions: selectMethod(FQMN)") void selectMethodByFullyQualifiedNamePreconditions(String fqmn, String message) { - Exception exception = assertThrows(PreconditionViolationException.class, () -> selectMethod(fqmn)); - assertThat(exception).hasMessageContaining(message); + assertPreconditionViolationFor(() -> selectMethod(fqmn)).withMessageContaining(message); } static Stream invalidFullyQualifiedMethodNames() { @@ -1525,7 +1523,7 @@ void selectsUniqueId() { // ------------------------------------------------------------------------- private void assertViolatesPrecondition(Executable precondition) { - assertThrows(PreconditionViolationException.class, precondition); + assertPreconditionViolationFor(precondition::execute); } private static DiscoverySelector parseIdentifier(DiscoverySelector selector) { diff --git a/platform-tests/src/test/java/org/junit/platform/engine/discovery/FilePositionTests.java b/platform-tests/src/test/java/org/junit/platform/engine/discovery/FilePositionTests.java index 8108bfd76a36..3c4b6e445f7a 100644 --- a/platform-tests/src/test/java/org/junit/platform/engine/discovery/FilePositionTests.java +++ b/platform-tests/src/test/java/org/junit/platform/engine/discovery/FilePositionTests.java @@ -12,9 +12,9 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.EqualsAndHashCodeAssertions.assertEqualsAndHashCode; import static org.junit.jupiter.params.provider.Arguments.arguments; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import java.util.stream.Stream; @@ -23,7 +23,6 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import org.junit.platform.commons.PreconditionViolationException; /** * Unit tests for {@link FilePosition}. @@ -36,8 +35,8 @@ class FilePositionTests { @Test @DisplayName("factory method preconditions") void preconditions() { - assertThrows(PreconditionViolationException.class, () -> FilePosition.from(-1)); - assertThrows(PreconditionViolationException.class, () -> FilePosition.from(0, -1)); + assertPreconditionViolationFor(() -> FilePosition.from(-1)); + assertPreconditionViolationFor(() -> FilePosition.from(0, -1)); } @Test diff --git a/platform-tests/src/test/java/org/junit/platform/engine/discovery/NestedClassSelectorTests.java b/platform-tests/src/test/java/org/junit/platform/engine/discovery/NestedClassSelectorTests.java index a06756041174..dc59d6833bcc 100644 --- a/platform-tests/src/test/java/org/junit/platform/engine/discovery/NestedClassSelectorTests.java +++ b/platform-tests/src/test/java/org/junit/platform/engine/discovery/NestedClassSelectorTests.java @@ -11,13 +11,12 @@ package org.junit.platform.engine.discovery; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.EqualsAndHashCodeAssertions.assertEqualsAndHashCode; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import java.util.List; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; /** * Unit tests for {@link NestedClassSelector}. @@ -43,10 +42,9 @@ void preservesOriginalExceptionWhenTryingToLoadEnclosingClasses() { var selector = new NestedClassSelector(null, List.of("org.example.EnclosingTestClass"), "org.example.NestedTestClass"); - var exception = assertThrows(PreconditionViolationException.class, selector::getEnclosingClasses); - - assertThat(exception).hasMessage("Could not load class with name: org.example.EnclosingTestClass") // - .hasCauseInstanceOf(ClassNotFoundException.class); + assertPreconditionViolationFor(selector::getEnclosingClasses).withMessage( + "Could not load class with name: org.example.EnclosingTestClass").withCauseInstanceOf( + ClassNotFoundException.class); } @Test @@ -54,10 +52,9 @@ void preservesOriginalExceptionWhenTryingToLoadNestedClass() { var selector = new NestedClassSelector(null, List.of("org.example.EnclosingTestClass"), "org.example.NestedTestClass"); - var exception = assertThrows(PreconditionViolationException.class, selector::getNestedClass); - - assertThat(exception).hasMessage("Could not load class with name: org.example.NestedTestClass") // - .hasCauseInstanceOf(ClassNotFoundException.class); + assertPreconditionViolationFor(selector::getNestedClass).withMessage( + "Could not load class with name: org.example.NestedTestClass").withCauseInstanceOf( + ClassNotFoundException.class); } @Test diff --git a/platform-tests/src/test/java/org/junit/platform/engine/discovery/NestedMethodSelectorTests.java b/platform-tests/src/test/java/org/junit/platform/engine/discovery/NestedMethodSelectorTests.java index 003721ff098e..3418be16188d 100644 --- a/platform-tests/src/test/java/org/junit/platform/engine/discovery/NestedMethodSelectorTests.java +++ b/platform-tests/src/test/java/org/junit/platform/engine/discovery/NestedMethodSelectorTests.java @@ -11,13 +11,12 @@ package org.junit.platform.engine.discovery; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.EqualsAndHashCodeAssertions.assertEqualsAndHashCode; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import java.util.List; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; /** * Unit tests for {@link NestedMethodSelector}. @@ -57,10 +56,8 @@ void preservesOriginalExceptionWhenTryingToLoadEnclosingClass() { var selector = new NestedMethodSelector(null, List.of("EnclosingClass"), "NestedTestClass", "method", "int, boolean"); - var exception = assertThrows(PreconditionViolationException.class, selector::getEnclosingClasses); - - assertThat(exception).hasMessage("Could not load class with name: EnclosingClass") // - .hasCauseInstanceOf(ClassNotFoundException.class); + assertPreconditionViolationFor(selector::getEnclosingClasses).withMessage( + "Could not load class with name: EnclosingClass").withCauseInstanceOf(ClassNotFoundException.class); } @Test @@ -68,10 +65,8 @@ void preservesOriginalExceptionWhenTryingToLoadNestedClass() { var selector = new NestedMethodSelector(null, List.of("EnclosingClass"), "NestedTestClass", "method", "int, boolean"); - var exception = assertThrows(PreconditionViolationException.class, selector::getNestedClass); - - assertThat(exception).hasMessage("Could not load class with name: NestedTestClass") // - .hasCauseInstanceOf(ClassNotFoundException.class); + assertPreconditionViolationFor(selector::getNestedClass).withMessage( + "Could not load class with name: NestedTestClass").withCauseInstanceOf(ClassNotFoundException.class); } @Test diff --git a/platform-tests/src/test/java/org/junit/platform/engine/discovery/PackageNameFilterTests.java b/platform-tests/src/test/java/org/junit/platform/engine/discovery/PackageNameFilterTests.java index 6f227908e454..b8441d6dcd4a 100644 --- a/platform-tests/src/test/java/org/junit/platform/engine/discovery/PackageNameFilterTests.java +++ b/platform-tests/src/test/java/org/junit/platform/engine/discovery/PackageNameFilterTests.java @@ -11,12 +11,12 @@ package org.junit.platform.engine.discovery; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotNullOrEmptyFor; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; /** * @since 1.0 @@ -26,15 +26,12 @@ class PackageNameFilterTests { @SuppressWarnings("DataFlowIssue") @Test void includePackageChecksPreconditions() { - assertThatThrownBy(() -> PackageNameFilter.includePackageNames((String[]) null)) // - .isInstanceOf(PreconditionViolationException.class) // - .hasMessage("packageNames array must not be null or empty"); - assertThatThrownBy(() -> PackageNameFilter.includePackageNames(new String[0])) // - .isInstanceOf(PreconditionViolationException.class) // - .hasMessage("packageNames array must not be null or empty"); - assertThatThrownBy(() -> PackageNameFilter.includePackageNames(new String[] { null })) // - .isInstanceOf(PreconditionViolationException.class) // - .hasMessage("packageNames array must not contain null elements"); + assertPreconditionViolationNotNullOrEmptyFor("packageNames array", + () -> PackageNameFilter.includePackageNames((String[]) null)); + assertPreconditionViolationNotNullOrEmptyFor("packageNames array", + () -> PackageNameFilter.includePackageNames(new String[0])); + assertPreconditionViolationFor(() -> PackageNameFilter.includePackageNames(new String[] { null })).withMessage( + "packageNames array must not contain null elements"); } @Test @@ -78,15 +75,12 @@ void includePackageWithMultiplePackages() { @SuppressWarnings("DataFlowIssue") @Test void excludePackageChecksPreconditions() { - assertThatThrownBy(() -> PackageNameFilter.excludePackageNames((String[]) null)) // - .isInstanceOf(PreconditionViolationException.class) // - .hasMessage("packageNames must not be null or empty"); - assertThatThrownBy(() -> PackageNameFilter.excludePackageNames(new String[0])) // - .isInstanceOf(PreconditionViolationException.class) // - .hasMessage("packageNames must not be null or empty"); - assertThatThrownBy(() -> PackageNameFilter.excludePackageNames(new String[] { null })) // - .isInstanceOf(PreconditionViolationException.class) // - .hasMessage("packageNames must not contain null elements"); + assertPreconditionViolationNotNullOrEmptyFor("packageNames", + () -> PackageNameFilter.excludePackageNames((String[]) null)); + assertPreconditionViolationNotNullOrEmptyFor("packageNames", + () -> PackageNameFilter.excludePackageNames(new String[0])); + assertPreconditionViolationFor(() -> PackageNameFilter.excludePackageNames(new String[] { null })).withMessage( + "packageNames must not contain null elements"); } @Test diff --git a/platform-tests/src/test/java/org/junit/platform/engine/support/config/PrefixedConfigurationParametersTests.java b/platform-tests/src/test/java/org/junit/platform/engine/support/config/PrefixedConfigurationParametersTests.java index dabfee86e9ac..0f1bf86f5cc5 100644 --- a/platform-tests/src/test/java/org/junit/platform/engine/support/config/PrefixedConfigurationParametersTests.java +++ b/platform-tests/src/test/java/org/junit/platform/engine/support/config/PrefixedConfigurationParametersTests.java @@ -11,7 +11,7 @@ package org.junit.platform.engine.support.config; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -21,7 +21,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.engine.ConfigurationParameters; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @@ -40,10 +39,10 @@ class PrefixedConfigurationParametersTests { @SuppressWarnings("DataFlowIssue") @Test void preconditions() { - assertThrows(PreconditionViolationException.class, () -> new PrefixedConfigurationParameters(null, "example.")); - assertThrows(PreconditionViolationException.class, () -> new PrefixedConfigurationParameters(delegate, null)); - assertThrows(PreconditionViolationException.class, () -> new PrefixedConfigurationParameters(delegate, "")); - assertThrows(PreconditionViolationException.class, () -> new PrefixedConfigurationParameters(delegate, " ")); + assertPreconditionViolationFor(() -> new PrefixedConfigurationParameters(null, "example.")); + assertPreconditionViolationFor(() -> new PrefixedConfigurationParameters(delegate, null)); + assertPreconditionViolationFor(() -> new PrefixedConfigurationParameters(delegate, "")); + assertPreconditionViolationFor(() -> new PrefixedConfigurationParameters(delegate, " ")); } @Test diff --git a/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/ClassSourceTests.java b/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/ClassSourceTests.java index 362a9d5bdb96..d0b4b1c91d6d 100644 --- a/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/ClassSourceTests.java +++ b/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/ClassSourceTests.java @@ -11,8 +11,8 @@ package org.junit.platform.engine.support.descriptor; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.EqualsAndHashCodeAssertions.assertEqualsAndHashCode; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import java.io.Serializable; import java.net.URI; @@ -20,7 +20,6 @@ import java.util.stream.Stream; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; /** * Unit tests for {@link ClassSource}. @@ -42,15 +41,15 @@ Stream createSerializableInstances() { @SuppressWarnings("DataFlowIssue") @Test void preconditions() { - assertThrows(PreconditionViolationException.class, () -> ClassSource.from((String) null)); - assertThrows(PreconditionViolationException.class, () -> ClassSource.from(" ")); - assertThrows(PreconditionViolationException.class, () -> ClassSource.from((String) null, null)); - assertThrows(PreconditionViolationException.class, () -> ClassSource.from(" ", null)); - assertThrows(PreconditionViolationException.class, () -> ClassSource.from((Class) null)); - assertThrows(PreconditionViolationException.class, () -> ClassSource.from((Class) null, null)); - assertThrows(PreconditionViolationException.class, () -> ClassSource.from((URI) null)); - assertThrows(PreconditionViolationException.class, () -> ClassSource.from(new URI("badscheme:/com.foo.Bar"))); - assertThrows(PreconditionViolationException.class, () -> ClassSource.from(new URI("class:?line=1"))); + assertPreconditionViolationFor(() -> ClassSource.from((String) null)); + assertPreconditionViolationFor(() -> ClassSource.from(" ")); + assertPreconditionViolationFor(() -> ClassSource.from((String) null, null)); + assertPreconditionViolationFor(() -> ClassSource.from(" ", null)); + assertPreconditionViolationFor(() -> ClassSource.from((Class) null)); + assertPreconditionViolationFor(() -> ClassSource.from((Class) null, null)); + assertPreconditionViolationFor(() -> ClassSource.from((URI) null)); + assertPreconditionViolationFor(() -> ClassSource.from(new URI("badscheme:/com.foo.Bar"))); + assertPreconditionViolationFor(() -> ClassSource.from(new URI("class:?line=1"))); } @Test @@ -61,8 +60,8 @@ void classSourceFromName() { assertThat(source.getClassName()).isEqualTo(testClassName); assertThat(source.getPosition()).isEmpty(); - var exception = assertThrows(PreconditionViolationException.class, source::getJavaClass); - assertThat(exception).hasMessage("Could not load class with name: " + testClassName); + assertPreconditionViolationFor(source::getJavaClass).withMessage( + "Could not load class with name: " + testClassName); } @Test diff --git a/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/ClasspathResourceSourceTests.java b/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/ClasspathResourceSourceTests.java index bb36abdccd3f..e5f1db8a5171 100644 --- a/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/ClasspathResourceSourceTests.java +++ b/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/ClasspathResourceSourceTests.java @@ -11,15 +11,14 @@ package org.junit.platform.engine.support.descriptor; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.EqualsAndHashCodeAssertions.assertEqualsAndHashCode; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import static org.junit.platform.engine.support.descriptor.ClasspathResourceSource.CLASSPATH_SCHEME; import java.net.URI; import java.util.stream.Stream; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; /** * Unit tests for {@link ClasspathResourceSource}. @@ -41,13 +40,12 @@ Stream createSerializableInstances() { @SuppressWarnings("DataFlowIssue") @Test void preconditions() { - assertThrows(PreconditionViolationException.class, () -> ClasspathResourceSource.from((String) null)); - assertThrows(PreconditionViolationException.class, () -> ClasspathResourceSource.from("")); - assertThrows(PreconditionViolationException.class, () -> ClasspathResourceSource.from(" ")); + assertPreconditionViolationFor(() -> ClasspathResourceSource.from((String) null)); + assertPreconditionViolationFor(() -> ClasspathResourceSource.from("")); + assertPreconditionViolationFor(() -> ClasspathResourceSource.from(" ")); - assertThrows(PreconditionViolationException.class, () -> ClasspathResourceSource.from((URI) null)); - assertThrows(PreconditionViolationException.class, - () -> ClasspathResourceSource.from(URI.create("file:/foo.txt"))); + assertPreconditionViolationFor(() -> ClasspathResourceSource.from((URI) null)); + assertPreconditionViolationFor(() -> ClasspathResourceSource.from(URI.create("file:/foo.txt"))); } @Test diff --git a/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/CompositeTestSourceTests.java b/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/CompositeTestSourceTests.java index cb53867cc682..6636172b7126 100644 --- a/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/CompositeTestSourceTests.java +++ b/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/CompositeTestSourceTests.java @@ -13,6 +13,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.EqualsAndHashCodeAssertions.assertEqualsAndHashCode; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import java.io.File; import java.util.ArrayList; @@ -20,7 +21,6 @@ import java.util.stream.Stream; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; /** * Unit tests for {@link CompositeTestSource}. @@ -40,12 +40,12 @@ Stream createSerializableInstances() { @SuppressWarnings("DataFlowIssue") @Test void createCompositeTestSourceFromNullList() { - assertThrows(PreconditionViolationException.class, () -> CompositeTestSource.from(null)); + assertPreconditionViolationFor(() -> CompositeTestSource.from(null)); } @Test void createCompositeTestSourceFromEmptyList() { - assertThrows(PreconditionViolationException.class, () -> CompositeTestSource.from(List.of())); + assertPreconditionViolationFor(() -> CompositeTestSource.from(List.of())); } @Test diff --git a/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/DefaultUriSourceTests.java b/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/DefaultUriSourceTests.java index 6b63fed65816..e1511d7e07af 100644 --- a/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/DefaultUriSourceTests.java +++ b/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/DefaultUriSourceTests.java @@ -12,14 +12,13 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.EqualsAndHashCodeAssertions.assertEqualsAndHashCode; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import java.net.URI; import java.util.stream.Stream; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; /** * Unit tests for {@link DefaultUriSource}. @@ -36,7 +35,7 @@ Stream createSerializableInstances() { @SuppressWarnings("DataFlowIssue") @Test void nullSourceUriYieldsException() { - assertThrows(PreconditionViolationException.class, () -> new DefaultUriSource(null)); + assertPreconditionViolationFor(() -> new DefaultUriSource(null)); } @Test diff --git a/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/FilePositionTests.java b/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/FilePositionTests.java index d1d85ae156d7..c7b4ec2047b5 100644 --- a/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/FilePositionTests.java +++ b/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/FilePositionTests.java @@ -12,9 +12,9 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.EqualsAndHashCodeAssertions.assertEqualsAndHashCode; import static org.junit.jupiter.params.provider.Arguments.arguments; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import java.util.stream.Stream; @@ -23,7 +23,6 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import org.junit.platform.commons.PreconditionViolationException; /** * Unit tests for {@link FilePosition}. @@ -41,8 +40,8 @@ Stream createSerializableInstances() { @Test @DisplayName("factory method preconditions") void preconditions() { - assertThrows(PreconditionViolationException.class, () -> FilePosition.from(-1)); - assertThrows(PreconditionViolationException.class, () -> FilePosition.from(0, -1)); + assertPreconditionViolationFor(() -> FilePosition.from(-1)); + assertPreconditionViolationFor(() -> FilePosition.from(0, -1)); } @Test diff --git a/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/FileSystemSourceTests.java b/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/FileSystemSourceTests.java index b05bae70d7b5..a3c59c01fd9b 100644 --- a/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/FileSystemSourceTests.java +++ b/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/FileSystemSourceTests.java @@ -11,14 +11,13 @@ package org.junit.platform.engine.support.descriptor; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.EqualsAndHashCodeAssertions.assertEqualsAndHashCode; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import java.io.File; import java.util.stream.Stream; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; /** * Unit tests for {@link FileSource} and {@link DirectorySource}. @@ -37,7 +36,7 @@ Stream createSerializableInstances() { @SuppressWarnings("DataFlowIssue") @Test void nullSourceFileOrDirectoryYieldsException() { - assertThrows(PreconditionViolationException.class, () -> FileSource.from(null)); + assertPreconditionViolationFor(() -> FileSource.from(null)); } @Test diff --git a/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/MethodSourceTests.java b/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/MethodSourceTests.java index 7f7f2ba4a6b3..ba29f7977e13 100644 --- a/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/MethodSourceTests.java +++ b/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/MethodSourceTests.java @@ -13,15 +13,14 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.EqualsAndHashCodeAssertions.assertEqualsAndHashCode; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import java.io.Serializable; import java.lang.reflect.Method; import java.util.stream.Stream; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; /** * Unit tests for {@link MethodSource}. @@ -60,34 +59,33 @@ void equalsAndHashCodeForMethodSource() throws Exception { @SuppressWarnings("DataFlowIssue") @Test void instantiatingWithNullNamesShouldThrowPreconditionViolationException() { - assertThrows(PreconditionViolationException.class, () -> MethodSource.from("foo", null)); - assertThrows(PreconditionViolationException.class, () -> MethodSource.from(null, "foo")); + assertPreconditionViolationFor(() -> MethodSource.from("foo", null)); + assertPreconditionViolationFor(() -> MethodSource.from(null, "foo")); } @Test void instantiatingWithEmptyNamesShouldThrowPreconditionViolationException() { - assertThrows(PreconditionViolationException.class, () -> MethodSource.from("foo", "")); - assertThrows(PreconditionViolationException.class, () -> MethodSource.from("", "foo")); + assertPreconditionViolationFor(() -> MethodSource.from("foo", "")); + assertPreconditionViolationFor(() -> MethodSource.from("", "foo")); } @Test void instantiatingWithBlankNamesShouldThrowPreconditionViolationException() { - assertThrows(PreconditionViolationException.class, () -> MethodSource.from("foo", " ")); - assertThrows(PreconditionViolationException.class, () -> MethodSource.from(" ", "foo")); + assertPreconditionViolationFor(() -> MethodSource.from("foo", " ")); + assertPreconditionViolationFor(() -> MethodSource.from(" ", "foo")); } @SuppressWarnings("DataFlowIssue") @Test void instantiationWithNullMethodShouldThrowPreconditionViolationException() { - assertThrows(PreconditionViolationException.class, () -> MethodSource.from(null)); + assertPreconditionViolationFor(() -> MethodSource.from(null)); } @SuppressWarnings("DataFlowIssue") @Test void instantiationWithNullClassOrMethodShouldThrowPreconditionViolationException() { - assertThrows(PreconditionViolationException.class, - () -> MethodSource.from(null, String.class.getDeclaredMethod("getBytes"))); - assertThrows(PreconditionViolationException.class, () -> MethodSource.from(String.class, null)); + assertPreconditionViolationFor(() -> MethodSource.from(null, String.class.getDeclaredMethod("getBytes"))); + assertPreconditionViolationFor(() -> MethodSource.from(String.class, null)); } @Test @@ -222,7 +220,7 @@ void getJavaClassFromString() { void getJavaClassShouldThrowExceptionIfClassNotFound() { var source = MethodSource.from(getClass().getName() + "X", "method1"); - assertThrows(PreconditionViolationException.class, source::getJavaClass); + assertPreconditionViolationFor(source::getJavaClass); } @Test @@ -253,21 +251,21 @@ void getJavaMethodFromStringShouldFindMethodWithParameter() throws Exception { void getJavaMethodFromStringShouldThrowExceptionIfParameterTypesAreNotSupplied() { var source = MethodSource.from(getClass().getName(), "method3"); - assertThrows(PreconditionViolationException.class, source::getJavaMethod); + assertPreconditionViolationFor(source::getJavaMethod); } @Test void getJavaMethodFromStringShouldThrowExceptionIfParameterTypesDoNotMatch() { var source = MethodSource.from(getClass().getName(), "method3", double.class); - assertThrows(PreconditionViolationException.class, source::getJavaMethod); + assertPreconditionViolationFor(source::getJavaMethod); } @Test void getJavaMethodFromStringShouldThrowExceptionIfMethodDoesNotExist() { var source = MethodSource.from(getClass().getName(), "methodX"); - assertThrows(PreconditionViolationException.class, source::getJavaMethod); + assertPreconditionViolationFor(source::getJavaMethod); } private Method getMethod(String name) throws Exception { diff --git a/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/PackageSourceTests.java b/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/PackageSourceTests.java index 5f55e05647bb..3d49a129c879 100644 --- a/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/PackageSourceTests.java +++ b/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/PackageSourceTests.java @@ -11,8 +11,8 @@ package org.junit.platform.engine.support.descriptor; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.EqualsAndHashCodeAssertions.assertEqualsAndHashCode; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import java.io.Serializable; import java.util.stream.Stream; @@ -20,7 +20,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; -import org.junit.platform.commons.PreconditionViolationException; /** * Unit tests for {@link PackageSource}. @@ -37,18 +36,18 @@ Stream createSerializableInstances() { @SuppressWarnings("DataFlowIssue") @Test void packageSourceFromNullPackageName() { - assertThrows(PreconditionViolationException.class, () -> PackageSource.from((String) null)); + assertPreconditionViolationFor(() -> PackageSource.from((String) null)); } @Test void packageSourceFromEmptyPackageName() { - assertThrows(PreconditionViolationException.class, () -> PackageSource.from(" ")); + assertPreconditionViolationFor(() -> PackageSource.from(" ")); } @SuppressWarnings("DataFlowIssue") @Test void packageSourceFromNullPackageReference() { - assertThrows(PreconditionViolationException.class, () -> PackageSource.from((Package) null)); + assertPreconditionViolationFor(() -> PackageSource.from((Package) null)); } @ParameterizedTest diff --git a/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/TestDescriptorOrderChildrenTests.java b/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/TestDescriptorOrderChildrenTests.java index e14f6c92e438..871683ecd945 100644 --- a/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/TestDescriptorOrderChildrenTests.java +++ b/platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/TestDescriptorOrderChildrenTests.java @@ -13,7 +13,7 @@ import static java.util.Collections.emptyList; import static java.util.Comparator.comparing; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import java.util.ArrayList; import java.util.List; @@ -21,7 +21,6 @@ import java.util.function.UnaryOperator; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.engine.TestDescriptor; import org.junit.platform.engine.UniqueId; @@ -55,9 +54,8 @@ default void orderChildrenInReverseOrder() { @Test default void orderChildrenEmptyList() { var testDescriptor = createTestDescriptorWithChildren(); - var exception = assertThrows(PreconditionViolationException.class, - () -> testDescriptor.orderChildren(children -> emptyList())); - assertThat(exception).hasMessage("orderer may not add or remove test descriptors"); + assertPreconditionViolationFor(() -> testDescriptor.orderChildren(children -> emptyList())).withMessage( + "orderer may not add or remove test descriptors"); } @Test @@ -79,8 +77,8 @@ default void orderChildrenRemovesDescriptor() { children.remove(1); return children; }; - var exception = assertThrows(PreconditionViolationException.class, () -> testDescriptor.orderChildren(orderer)); - assertThat(exception).hasMessage("orderer may not add or remove test descriptors"); + assertPreconditionViolationFor(() -> testDescriptor.orderChildren(orderer)).withMessage( + "orderer may not add or remove test descriptors"); } @Test @@ -90,8 +88,8 @@ default void orderChildrenAddsDescriptor() { children.add(1, new StubTestDescriptor(UniqueId.root("extra", "extra1"))); return children; }; - var exception = assertThrows(PreconditionViolationException.class, () -> testDescriptor.orderChildren(orderer)); - assertThat(exception).hasMessage("orderer may not add or remove test descriptors"); + assertPreconditionViolationFor(() -> testDescriptor.orderChildren(orderer)).withMessage( + "orderer may not add or remove test descriptors"); } @Test @@ -101,8 +99,8 @@ default void orderChildrenReplacesDescriptor() { children.set(1, new StubTestDescriptor(UniqueId.root("replaced", "replaced1"))); return children; }; - var exception = assertThrows(PreconditionViolationException.class, () -> testDescriptor.orderChildren(orderer)); - assertThat(exception).hasMessage("orderer may not add or remove test descriptors"); + assertPreconditionViolationFor(() -> testDescriptor.orderChildren(orderer)).withMessage( + "orderer may not add or remove test descriptors"); } @Test @@ -112,17 +110,16 @@ default void orderChildrenDuplicatesDescriptor() { children.add(1, children.getLast()); return children; }; - var exception = assertThrows(PreconditionViolationException.class, () -> testDescriptor.orderChildren(orderer)); - assertThat(exception).hasMessage("orderer may not add or remove test descriptors"); + assertPreconditionViolationFor(() -> testDescriptor.orderChildren(orderer)).withMessage( + "orderer may not add or remove test descriptors"); } @SuppressWarnings("DataFlowIssue") @Test default void orderChildrenOrdererReturnsNull() { var testDescriptor = createTestDescriptorWithChildren(); - var exception = assertThrows(PreconditionViolationException.class, - () -> testDescriptor.orderChildren(children -> null)); - assertThat(exception).hasMessage("orderer may not return null"); + assertPreconditionViolationFor(() -> testDescriptor.orderChildren(children -> null)).withMessage( + "orderer may not return null"); } @Test diff --git a/platform-tests/src/test/java/org/junit/platform/launcher/MethodFilterTests.java b/platform-tests/src/test/java/org/junit/platform/launcher/MethodFilterTests.java index 14b8d8bd1d3b..8a30d5d3a637 100644 --- a/platform-tests/src/test/java/org/junit/platform/launcher/MethodFilterTests.java +++ b/platform-tests/src/test/java/org/junit/platform/launcher/MethodFilterTests.java @@ -11,13 +11,13 @@ package org.junit.platform.launcher; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotNullOrEmptyFor; import static org.junit.platform.launcher.MethodFilter.excludeMethodNamePatterns; import static org.junit.platform.launcher.MethodFilter.includeMethodNamePatterns; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.commons.util.ReflectionUtils; import org.junit.platform.engine.FilterResult; import org.junit.platform.engine.TestDescriptor; @@ -42,15 +42,11 @@ class MethodFilterTests { @SuppressWarnings("DataFlowIssue") @Test void includeMethodNamePatternsChecksPreconditions() { - assertThatThrownBy(() -> includeMethodNamePatterns((String[]) null)) // - .isInstanceOf(PreconditionViolationException.class) // - .hasMessage("patterns array must not be null or empty"); - assertThatThrownBy(() -> includeMethodNamePatterns(new String[0])) // - .isInstanceOf(PreconditionViolationException.class) // - .hasMessage("patterns array must not be null or empty"); - assertThatThrownBy(() -> includeMethodNamePatterns(new String[] { null })) // - .isInstanceOf(PreconditionViolationException.class) // - .hasMessage("patterns array must not contain null elements"); + assertPreconditionViolationNotNullOrEmptyFor("patterns array", + () -> includeMethodNamePatterns((String[]) null)); + assertPreconditionViolationNotNullOrEmptyFor("patterns array", () -> includeMethodNamePatterns(new String[0])); + assertPreconditionViolationFor(() -> includeMethodNamePatterns(new String[] { null })).withMessage( + "patterns array must not contain null elements"); } @Test @@ -90,15 +86,11 @@ void includeMultipleMethodNamePatterns() { @SuppressWarnings("DataFlowIssue") @Test void excludeMethodNamePatternsChecksPreconditions() { - assertThatThrownBy(() -> excludeMethodNamePatterns((String[]) null)) // - .isInstanceOf(PreconditionViolationException.class) // - .hasMessage("patterns array must not be null or empty"); - assertThatThrownBy(() -> excludeMethodNamePatterns(new String[0])) // - .isInstanceOf(PreconditionViolationException.class) // - .hasMessage("patterns array must not be null or empty"); - assertThatThrownBy(() -> excludeMethodNamePatterns(new String[] { null })) // - .isInstanceOf(PreconditionViolationException.class) // - .hasMessage("patterns array must not contain null elements"); + assertPreconditionViolationNotNullOrEmptyFor("patterns array", + () -> excludeMethodNamePatterns((String[]) null)); + assertPreconditionViolationNotNullOrEmptyFor("patterns array", () -> excludeMethodNamePatterns(new String[0])); + assertPreconditionViolationFor(() -> excludeMethodNamePatterns(new String[] { null })).withMessage( + "patterns array must not contain null elements"); } @Test diff --git a/platform-tests/src/test/java/org/junit/platform/launcher/TagFilterTests.java b/platform-tests/src/test/java/org/junit/platform/launcher/TagFilterTests.java index e27e9d25addb..e1eae9bdd8af 100644 --- a/platform-tests/src/test/java/org/junit/platform/launcher/TagFilterTests.java +++ b/platform-tests/src/test/java/org/junit/platform/launcher/TagFilterTests.java @@ -12,8 +12,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertAll; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import static org.junit.platform.launcher.TagFilter.excludeTags; import static org.junit.platform.launcher.TagFilter.includeTags; @@ -23,7 +23,6 @@ import org.jspecify.annotations.Nullable; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.engine.FilterResult; import org.junit.platform.engine.TestDescriptor; import org.junit.platform.engine.UniqueId; @@ -63,8 +62,8 @@ void includeTagsWithInvalidSyntax() { @SuppressWarnings("DataFlowIssue") private void assertSyntaxViolationForIncludes(@Nullable String tag) { - var exception = assertThrows(PreconditionViolationException.class, () -> includeTags(tag)); - assertThat(exception).hasMessageStartingWith("Unable to parse tag expression"); + assertPreconditionViolationFor(() -> includeTags(tag)).withMessageStartingWith( + "Unable to parse tag expression"); } @Test @@ -81,8 +80,8 @@ void excludeTagsWithInvalidSyntax() { @SuppressWarnings("DataFlowIssue") private void assertSyntaxViolationForExcludes(@Nullable String tag) { - var exception = assertThrows(PreconditionViolationException.class, () -> excludeTags(tag)); - assertThat(exception).hasMessageStartingWith("Unable to parse tag expression"); + assertPreconditionViolationFor(() -> excludeTags(tag)).withMessageStartingWith( + "Unable to parse tag expression"); } @Test @@ -136,17 +135,16 @@ void excludeMultipleTags() { @Test void rejectSingleUnparsableTagExpressions() { var brokenTagExpression = "tag & "; - RuntimeException expected = assertThrows(PreconditionViolationException.class, - () -> TagFilter.includeTags(brokenTagExpression)); - assertThat(expected).hasMessageStartingWith("Unable to parse tag expression \"" + brokenTagExpression + "\""); + assertPreconditionViolationFor(() -> TagFilter.includeTags(brokenTagExpression)).withMessageStartingWith( + "Unable to parse tag expression \"" + brokenTagExpression + "\""); } @Test void rejectUnparsableTagExpressionFromArray() { var brokenTagExpression = "tag & "; - RuntimeException expected = assertThrows(PreconditionViolationException.class, - () -> TagFilter.excludeTags(brokenTagExpression, "foo", "bar")); - assertThat(expected).hasMessageStartingWith("Unable to parse tag expression \"" + brokenTagExpression + "\""); + assertPreconditionViolationFor( + () -> TagFilter.excludeTags(brokenTagExpression, "foo", "bar")).withMessageStartingWith( + "Unable to parse tag expression \"" + brokenTagExpression + "\""); } private void includeSingleTag(PostDiscoveryFilter filter) { diff --git a/platform-tests/src/test/java/org/junit/platform/launcher/core/DefaultLauncherTests.java b/platform-tests/src/test/java/org/junit/platform/launcher/core/DefaultLauncherTests.java index 4be05fe60846..bea65bd693dc 100644 --- a/platform-tests/src/test/java/org/junit/platform/launcher/core/DefaultLauncherTests.java +++ b/platform-tests/src/test/java/org/junit/platform/launcher/core/DefaultLauncherTests.java @@ -17,6 +17,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import static org.junit.platform.commons.util.CollectionUtils.getOnlyElement; import static org.junit.platform.engine.SelectorResolutionResult.unresolved; import static org.junit.platform.engine.TestExecutionResult.Status.ABORTED; @@ -56,7 +57,6 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.junit.platform.commons.JUnitException; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.commons.logging.LogRecordListener; import org.junit.platform.commons.util.ExceptionUtils; import org.junit.platform.engine.CancellationToken; @@ -105,10 +105,8 @@ class DefaultLauncherTests { void constructLauncherWithoutAnyEngines() { var launcher = createLauncher(); - Throwable exception = assertThrows(PreconditionViolationException.class, - () -> launcher.discover(request().build())); - - assertThat(exception).hasMessageContaining("Cannot create Launcher without at least one TestEngine"); + assertPreconditionViolationFor(() -> launcher.discover(request().build())).withMessageContaining( + "Cannot create Launcher without at least one TestEngine"); } @Test @@ -602,8 +600,8 @@ void launcherCanExecuteTestPlanExactlyOnce() { launcher.execute(executionRequest); verify(engine, times(1)).execute(any()); - var e = assertThrows(PreconditionViolationException.class, () -> launcher.execute(executionRequest)); - assertEquals("TestPlan must only be executed once", e.getMessage()); + assertPreconditionViolationFor(() -> launcher.execute(executionRequest)).withMessage( + "TestPlan must only be executed once"); } @Test diff --git a/platform-tests/src/test/java/org/junit/platform/launcher/core/EngineDiscoveryResultValidatorTests.java b/platform-tests/src/test/java/org/junit/platform/launcher/core/EngineDiscoveryResultValidatorTests.java index 854c3bcefdf4..d08c94f48b11 100644 --- a/platform-tests/src/test/java/org/junit/platform/launcher/core/EngineDiscoveryResultValidatorTests.java +++ b/platform-tests/src/test/java/org/junit/platform/launcher/core/EngineDiscoveryResultValidatorTests.java @@ -10,10 +10,9 @@ package org.junit.platform.launcher.core; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.engine.TestDescriptor; import org.junit.platform.engine.TestEngine; import org.junit.platform.engine.UniqueId; @@ -34,13 +33,11 @@ void detectCycleWithDoubleRoot() { validator.validate(testEngine, root); root.addChild(root); - assertThatThrownBy(() -> validator.validate(testEngine, root)) // - .isInstanceOf(PreconditionViolationException.class) // - .hasMessage(""" - The discover() method for TestEngine with ID 'my-engine' returned a cyclic graph; \ - [engine:root] exists in at least two paths: - (1) [engine:root] - (2) [engine:root] -> [engine:root]"""); + assertPreconditionViolationFor(() -> validator.validate(testEngine, root)).withMessage(""" + The discover() method for TestEngine with ID 'my-engine' returned a cyclic graph; \ + [engine:root] exists in at least two paths: + (1) [engine:root] + (2) [engine:root] -> [engine:root]"""); } @Test @@ -54,13 +51,11 @@ void detectCycleWithDoubleGroup() { validator.validate(testEngine, root); group2.addChild(group1); - assertThatThrownBy(() -> validator.validate(testEngine, root)) // - .isInstanceOf(PreconditionViolationException.class) // - .hasMessage(""" - The discover() method for TestEngine with ID 'my-engine' returned a cyclic graph; \ - [engine:root]/[group:1] exists in at least two paths: - (1) [engine:root] -> [engine:root]/[group:1] - (2) [engine:root] -> [engine:root]/[group:2] -> [engine:root]/[group:1]"""); + assertPreconditionViolationFor(() -> validator.validate(testEngine, root)).withMessage(""" + The discover() method for TestEngine with ID 'my-engine' returned a cyclic graph; \ + [engine:root]/[group:1] exists in at least two paths: + (1) [engine:root] -> [engine:root]/[group:1] + (2) [engine:root] -> [engine:root]/[group:2] -> [engine:root]/[group:1]"""); } @Test @@ -78,13 +73,11 @@ void detectCycleWithDoubleTest() { validator.validate(testEngine, root); group2.addChild(test1); - assertThatThrownBy(() -> validator.validate(testEngine, root)) // - .isInstanceOf(PreconditionViolationException.class) // - .hasMessage(""" - The discover() method for TestEngine with ID 'my-engine' returned a cyclic graph; \ - [engine:root]/[group:1]/[test:1] exists in at least two paths: - (1) [engine:root] -> [engine:root]/[group:1] -> [engine:root]/[group:1]/[test:1] - (2) [engine:root] -> [engine:root]/[group:2] -> [engine:root]/[group:1]/[test:1]"""); + assertPreconditionViolationFor(() -> validator.validate(testEngine, root)).withMessage(""" + The discover() method for TestEngine with ID 'my-engine' returned a cyclic graph; \ + [engine:root]/[group:1]/[test:1] exists in at least two paths: + (1) [engine:root] -> [engine:root]/[group:1] -> [engine:root]/[group:1]/[test:1] + (2) [engine:root] -> [engine:root]/[group:2] -> [engine:root]/[group:1]/[test:1]"""); } } diff --git a/platform-tests/src/test/java/org/junit/platform/launcher/core/LauncherConfigTests.java b/platform-tests/src/test/java/org/junit/platform/launcher/core/LauncherConfigTests.java index 0dda349b3b01..48bd6ade7309 100644 --- a/platform-tests/src/test/java/org/junit/platform/launcher/core/LauncherConfigTests.java +++ b/platform-tests/src/test/java/org/junit/platform/launcher/core/LauncherConfigTests.java @@ -12,11 +12,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.engine.TestEngine; import org.junit.platform.fakes.TestEngineStub; import org.junit.platform.launcher.LauncherDiscoveryListener; @@ -33,17 +32,15 @@ class LauncherConfigTests { @SuppressWarnings("DataFlowIssue") @Test void preconditions() { - assertThrows(PreconditionViolationException.class, - () -> LauncherConfig.builder().addTestEngines((TestEngine[]) null)); - assertThrows(PreconditionViolationException.class, + assertPreconditionViolationFor(() -> LauncherConfig.builder().addTestEngines((TestEngine[]) null)); + assertPreconditionViolationFor( () -> LauncherConfig.builder().addTestExecutionListeners((TestExecutionListener[]) null)); TestEngine engine = new TestEngineStub(); var listener = new TestExecutionListener() { }; - assertThrows(PreconditionViolationException.class, - () -> LauncherConfig.builder().addTestEngines(engine, engine, null)); - assertThrows(PreconditionViolationException.class, + assertPreconditionViolationFor(() -> LauncherConfig.builder().addTestEngines(engine, engine, null)); + assertPreconditionViolationFor( () -> LauncherConfig.builder().addTestExecutionListeners(listener, listener, null)); } diff --git a/platform-tests/src/test/java/org/junit/platform/launcher/core/LauncherConfigurationParametersTests.java b/platform-tests/src/test/java/org/junit/platform/launcher/core/LauncherConfigurationParametersTests.java index 62f2d578994d..609e246496e4 100644 --- a/platform-tests/src/test/java/org/junit/platform/launcher/core/LauncherConfigurationParametersTests.java +++ b/platform-tests/src/test/java/org/junit/platform/launcher/core/LauncherConfigurationParametersTests.java @@ -14,6 +14,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import java.net.URL; import java.net.URLClassLoader; @@ -34,7 +35,6 @@ import org.junit.jupiter.api.fixtures.TrackLogRecords; import org.junit.jupiter.api.io.TempDir; import org.junit.platform.commons.JUnitException; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.commons.logging.LogRecordListener; import org.junit.platform.engine.ConfigurationParameters; import org.junit.platform.engine.discovery.DiscoverySelectors; @@ -63,19 +63,19 @@ void reset() { @SuppressWarnings("DataFlowIssue") @Test void constructorPreconditions() { - assertThrows(PreconditionViolationException.class, () -> fromMap(null)); - assertThrows(PreconditionViolationException.class, () -> fromMapAndFile(Map.of(), null)); - assertThrows(PreconditionViolationException.class, () -> fromMapAndFile(Map.of(), "")); - assertThrows(PreconditionViolationException.class, () -> fromMapAndFile(Map.of(), " ")); + assertPreconditionViolationFor(() -> fromMap(null)); + assertPreconditionViolationFor(() -> fromMapAndFile(Map.of(), null)); + assertPreconditionViolationFor(() -> fromMapAndFile(Map.of(), "")); + assertPreconditionViolationFor(() -> fromMapAndFile(Map.of(), " ")); } @SuppressWarnings("DataFlowIssue") @Test void getPreconditions() { ConfigurationParameters configParams = fromMap(Map.of()); - assertThrows(PreconditionViolationException.class, () -> configParams.get(null)); - assertThrows(PreconditionViolationException.class, () -> configParams.get("")); - assertThrows(PreconditionViolationException.class, () -> configParams.get(" ")); + assertPreconditionViolationFor(() -> configParams.get(null)); + assertPreconditionViolationFor(() -> configParams.get("")); + assertPreconditionViolationFor(() -> configParams.get(" ")); } @Test diff --git a/platform-tests/src/test/java/org/junit/platform/launcher/core/LauncherDiscoveryRequestBuilderTests.java b/platform-tests/src/test/java/org/junit/platform/launcher/core/LauncherDiscoveryRequestBuilderTests.java index fa8d42498dbb..cd55b1ef7323 100644 --- a/platform-tests/src/test/java/org/junit/platform/launcher/core/LauncherDiscoveryRequestBuilderTests.java +++ b/platform-tests/src/test/java/org/junit/platform/launcher/core/LauncherDiscoveryRequestBuilderTests.java @@ -11,8 +11,8 @@ package org.junit.platform.launcher.core; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import static org.junit.platform.engine.FilterResult.excluded; import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass; import static org.junit.platform.engine.discovery.DiscoverySelectors.selectMethod; @@ -32,7 +32,6 @@ import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.engine.DiscoveryFilter; import org.junit.platform.engine.TestEngine; import org.junit.platform.engine.UniqueId; @@ -226,12 +225,10 @@ void postDiscoveryFiltersAreStoredInDiscoveryRequest() { @Test void exceptionForIllegalFilterClass() { - Exception exception = assertThrows(PreconditionViolationException.class, - () -> discoveryRequest().filters(o -> excluded("reason"))); - - assertThat(exception).hasMessageStartingWith("Filter"); - assertThat(exception).hasMessageEndingWith( - "must implement EngineFilter, PostDiscoveryFilter, or DiscoveryFilter."); + assertPreconditionViolationFor( + () -> discoveryRequest().filters(o -> excluded("reason"))).withMessageStartingWith( + "Filter").withMessageEndingWith( + "must implement EngineFilter, PostDiscoveryFilter, or DiscoveryFilter."); } } diff --git a/platform-tests/src/test/java/org/junit/platform/launcher/core/LauncherFactoryTests.java b/platform-tests/src/test/java/org/junit/platform/launcher/core/LauncherFactoryTests.java index 3067356d1951..47448ceaaaf2 100644 --- a/platform-tests/src/test/java/org/junit/platform/launcher/core/LauncherFactoryTests.java +++ b/platform-tests/src/test/java/org/junit/platform/launcher/core/LauncherFactoryTests.java @@ -16,6 +16,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.TemporaryClasspathExecutor.withAdditionalClasspathRoot; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass; import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClasses; import static org.junit.platform.launcher.LauncherConstants.DEACTIVATE_LISTENERS_PATTERN_PROPERTY_NAME; @@ -33,7 +34,6 @@ import org.junit.jupiter.api.extension.ExtensionContext.StoreScope; import org.junit.jupiter.api.fixtures.TrackLogRecords; import org.junit.jupiter.engine.JupiterTestEngine; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.commons.logging.LogRecordListener; import org.junit.platform.engine.EngineDiscoveryRequest; import org.junit.platform.engine.ExecutionRequest; @@ -67,7 +67,7 @@ class LauncherFactoryTests { @SuppressWarnings("DataFlowIssue") @Test void preconditions() { - assertThrows(PreconditionViolationException.class, () -> LauncherFactory.create(null)); + assertPreconditionViolationFor(() -> LauncherFactory.create(null)); } @Test diff --git a/platform-tests/src/test/java/org/junit/platform/launcher/core/LauncherSessionTests.java b/platform-tests/src/test/java/org/junit/platform/launcher/core/LauncherSessionTests.java index 0cef6ce6f90c..1f07342510ce 100644 --- a/platform-tests/src/test/java/org/junit/platform/launcher/core/LauncherSessionTests.java +++ b/platform-tests/src/test/java/org/junit/platform/launcher/core/LauncherSessionTests.java @@ -10,7 +10,7 @@ package org.junit.platform.launcher.core; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import static org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder.discoveryRequest; import static org.junit.platform.launcher.core.LauncherExecutionRequestBuilder.executionRequest; import static org.junit.platform.launcher.core.LauncherFactoryForTestingPurposesOnly.createLauncherConfigBuilderWithDisabledServiceLoading; @@ -19,7 +19,6 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.fakes.TestEngineStub; import org.junit.platform.launcher.LauncherDiscoveryRequest; import org.junit.platform.launcher.LauncherSession; @@ -122,12 +121,11 @@ void closedSessionCannotBeUsed() { session.close(); - assertThrows(PreconditionViolationException.class, () -> launcher.discover(discoveryRequest)); - assertThrows(PreconditionViolationException.class, () -> launcher.execute(testPlan)); - assertThrows(PreconditionViolationException.class, () -> launcher.execute(discoveryRequest)); - assertThrows(PreconditionViolationException.class, () -> launcher.execute(executionRequest(testPlan).build())); - assertThrows(PreconditionViolationException.class, - () -> launcher.execute(executionRequest(discoveryRequest).build())); + assertPreconditionViolationFor(() -> launcher.discover(discoveryRequest)); + assertPreconditionViolationFor(() -> launcher.execute(testPlan)); + assertPreconditionViolationFor(() -> launcher.execute(discoveryRequest)); + assertPreconditionViolationFor(() -> launcher.execute(executionRequest(testPlan).build())); + assertPreconditionViolationFor(() -> launcher.execute(executionRequest(discoveryRequest).build())); } } diff --git a/platform-tests/src/test/java/org/junit/platform/launcher/core/ListenerRegistryTests.java b/platform-tests/src/test/java/org/junit/platform/launcher/core/ListenerRegistryTests.java index c60475a6196f..3e44ea564ae2 100644 --- a/platform-tests/src/test/java/org/junit/platform/launcher/core/ListenerRegistryTests.java +++ b/platform-tests/src/test/java/org/junit/platform/launcher/core/ListenerRegistryTests.java @@ -10,13 +10,12 @@ package org.junit.platform.launcher.core; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotNullFor; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotNullOrEmptyFor; import java.util.List; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; public class ListenerRegistryTests { @@ -25,18 +24,14 @@ public class ListenerRegistryTests { void registerWithNullArray() { var registry = ListenerRegistry.create(List::getFirst); - var exception = assertThrows(PreconditionViolationException.class, () -> registry.addAll((Object[]) null)); - - assertThat(exception).hasMessageContaining("listeners array must not be null or empty"); + assertPreconditionViolationNotNullOrEmptyFor("listeners array", () -> registry.addAll((Object[]) null)); } @Test void registerWithEmptyArray() { var registry = ListenerRegistry.create(List::getFirst); - var exception = assertThrows(PreconditionViolationException.class, registry::addAll); - - assertThat(exception).hasMessageContaining("listeners array must not be null or empty"); + assertPreconditionViolationNotNullOrEmptyFor("listeners array", registry::addAll); } @SuppressWarnings("DataFlowIssue") @@ -44,9 +39,6 @@ void registerWithEmptyArray() { void registerWithArrayContainingNullElements() { var registry = ListenerRegistry.create(List::getFirst); - var exception = assertThrows(PreconditionViolationException.class, - () -> registry.addAll(new Object[] { null })); - - assertThat(exception).hasMessageContaining("individual listeners must not be null"); + assertPreconditionViolationNotNullFor("individual listeners", () -> registry.addAll(new Object[] { null })); } } diff --git a/platform-tests/src/test/java/org/junit/platform/launcher/tagexpression/TagExpressionsTests.java b/platform-tests/src/test/java/org/junit/platform/launcher/tagexpression/TagExpressionsTests.java index 1133b03f5d7e..35a7f871a5af 100644 --- a/platform-tests/src/test/java/org/junit/platform/launcher/tagexpression/TagExpressionsTests.java +++ b/platform-tests/src/test/java/org/junit/platform/launcher/tagexpression/TagExpressionsTests.java @@ -11,7 +11,7 @@ package org.junit.platform.launcher.tagexpression; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import static org.junit.platform.engine.TestTag.create; import static org.junit.platform.launcher.tagexpression.TagExpressions.and; import static org.junit.platform.launcher.tagexpression.TagExpressions.any; @@ -23,7 +23,6 @@ import java.util.Set; import org.junit.jupiter.api.Test; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.engine.TestTag; class TagExpressionsTests { @@ -38,9 +37,8 @@ void tagIsJustATestTag() { @Test void rejectInvalidTestTags() { - RuntimeException expected = assertThrows(PreconditionViolationException.class, - () -> tag("tags with spaces are not allowed")); - assertThat(expected).hasMessageContaining("tags with spaces are not allowed"); + assertPreconditionViolationFor(() -> tag("tags with spaces are not allowed")).withMessageContaining( + "tags with spaces are not allowed"); } @Test diff --git a/platform-tests/src/test/java/org/junit/platform/suite/engine/SuiteLauncherDiscoveryRequestBuilderTests.java b/platform-tests/src/test/java/org/junit/platform/suite/engine/SuiteLauncherDiscoveryRequestBuilderTests.java index b44896289d7e..4a19a2b55dc5 100644 --- a/platform-tests/src/test/java/org/junit/platform/suite/engine/SuiteLauncherDiscoveryRequestBuilderTests.java +++ b/platform-tests/src/test/java/org/junit/platform/suite/engine/SuiteLauncherDiscoveryRequestBuilderTests.java @@ -14,9 +14,9 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.DynamicTest.dynamicTest; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; import static org.junit.platform.suite.engine.SuiteLauncherDiscoveryRequestBuilder.request; import java.lang.annotation.Retention; @@ -34,7 +34,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestFactory; import org.junit.jupiter.engine.JupiterTestEngine; -import org.junit.platform.commons.PreconditionViolationException; import org.junit.platform.commons.util.CollectionUtils; import org.junit.platform.engine.ConfigurationParameters; import org.junit.platform.engine.TestDescriptor; @@ -288,12 +287,10 @@ void selectClassesWithoutReferencesOrNames() { class Suite { } - var e = assertThrows(PreconditionViolationException.class, - () -> builder.applySelectorsAndFiltersFromSuite(Suite.class)); - - assertThat(e).hasMessageMatching( - "@SelectClasses on class \\[" + Pattern.quote(SuiteLauncherDiscoveryRequestBuilderTests.class.getName()) - + "\\$\\d+Suite] must declare at least one class reference or name"); + assertPreconditionViolationFor( + () -> builder.applySelectorsAndFiltersFromSuite(Suite.class)).withMessageMatching( + "@SelectClasses on class \\[" + Pattern.quote(SuiteLauncherDiscoveryRequestBuilderTests.class.getName()) + + "\\$\\d+Suite] must declare at least one class reference or name"); } static class NonLocalTestCase { @@ -430,11 +427,9 @@ class ParameterTypesAndParameterTypeNames { Class suiteClassName = entry.getKey(); var expectedFailureMessage = entry.getValue(); return dynamicTest(suiteClassName.getSimpleName(), () -> { - var ex = assertThrows(PreconditionViolationException.class, - () -> request().applySelectorsAndFiltersFromSuite(suiteClassName)); - assertEquals( - "@SelectMethod on class [" + suiteClassName.getName() + "]: " + expectedFailureMessage, - ex.getMessage()); + assertPreconditionViolationFor( + () -> request().applySelectorsAndFiltersFromSuite(suiteClassName)).withMessage( + "@SelectMethod on class [" + suiteClassName.getName() + "]: " + expectedFailureMessage); }); }); } diff --git a/platform-tests/src/test/java/org/junit/platform/testkit/engine/NestedContainerEventConditionTests.java b/platform-tests/src/test/java/org/junit/platform/testkit/engine/NestedContainerEventConditionTests.java index 56b64d18eab0..8ca4d0ad4b4c 100644 --- a/platform-tests/src/test/java/org/junit/platform/testkit/engine/NestedContainerEventConditionTests.java +++ b/platform-tests/src/test/java/org/junit/platform/testkit/engine/NestedContainerEventConditionTests.java @@ -13,6 +13,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotNullFor; import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass; import static org.junit.platform.testkit.engine.EventConditions.container; import static org.junit.platform.testkit.engine.EventConditions.displayName; @@ -43,8 +44,7 @@ class NestedContainerEventConditionTests { @SuppressWarnings("DataFlowIssue") @Test void preconditions() { - assertPreconditionViolationFor(() -> nestedContainer(null))// - .withMessage("Class must not be null"); + assertPreconditionViolationNotNullFor("Class", () -> nestedContainer(null)); assertPreconditionViolationFor(() -> nestedContainer(NestedContainerEventConditionTests.class))// .withMessage(NestedContainerEventConditionTests.class.getName() + " must be a nested class"); diff --git a/platform-tests/src/test/java/org/junit/platform/testkit/engine/TestExecutionResultConditionsTests.java b/platform-tests/src/test/java/org/junit/platform/testkit/engine/TestExecutionResultConditionsTests.java index d60450a365c2..5d165c65f17d 100644 --- a/platform-tests/src/test/java/org/junit/platform/testkit/engine/TestExecutionResultConditionsTests.java +++ b/platform-tests/src/test/java/org/junit/platform/testkit/engine/TestExecutionResultConditionsTests.java @@ -12,6 +12,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationFor; +import static org.junit.platform.commons.test.PreconditionAssertions.assertPreconditionViolationNotNullFor; import static org.junit.platform.testkit.engine.TestExecutionResultConditions.message; import static org.junit.platform.testkit.engine.TestExecutionResultConditions.rootCause; @@ -33,8 +34,7 @@ class TestExecutionResultConditionsTests { @Test void rootCauseFailsForNullThrowable() { - assertPreconditionViolationFor(() -> rootCauseCondition.matches(null))// - .withMessage("Throwable must not be null"); + assertPreconditionViolationNotNullFor("Throwable", () -> rootCauseCondition.matches(null)); } @Test