From 125159303a7165411f24e378273969de0c415754 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mih=C3=A1ly=20Verh=C3=A1s?= Date: Tue, 26 Mar 2024 12:25:23 +0100 Subject: [PATCH] Small improvements and fixes (#790 / #800) Numerous small improvements and polishing, for example touch-up of the "demo" project. Closes: #790 PR: #800 --- .github/workflows/build.yml | 2 +- .infra/checkstyle/import-control.xml | 1 + build.gradle.kts | 3 +- .../DisableIfTestFailsExtensionDemo.java | 8 +- .../jupiter/ExpectedToFailExtensionDemo.java | 6 +- .../jupiter/StdInOutExtensionDemo.java | 4 +- .../cartesian/BitArgumentProvider.java | 1 + .../cartesian/CartesianTestExtensionDemo.java | 12 +- .../jupiter/cartesian/MyTestReporter.java | 24 - .../cartesian/NumberArgumentProvider.java | 3 +- .../cartesian/PeopleProviderSources.java | 7 +- .../DisableParameterizedExtensionDemo.java | 2 +- .../jupiter/resource/InMemoryDirectory.java | 8 +- .../resource/ResourceExtensionDemo.java | 74 +-- .../internal/PioneerPreconditions.java | 16 +- .../jupiter/ExpectedToFailExtension.java | 5 +- .../jupiter/resource/ResourceExtension.java | 47 +- .../jupiter/DisableIfTestFailsTests.java | 6 +- .../jupiter/ExpectedToFailExtensionTests.java | 13 +- .../jupiter/ReportEntryExtensionTests.java | 12 +- .../IssueExtensionExecutionListenerTests.java | 13 +- .../params/DisabledIfNameExtensionTests.java | 2 +- .../jupiter/resource/PathDeleterTests.java | 12 +- .../jupiter/resource/ResourcesTests.java | 432 +++++++----------- .../resource/TemporaryDirectoryTests.java | 2 +- 25 files changed, 306 insertions(+), 409 deletions(-) delete mode 100644 src/demo/java/org/junitpioneer/jupiter/cartesian/MyTestReporter.java diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 9253dc652..f129d82ce 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -98,7 +98,7 @@ jobs: env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} SONAR_TOKEN: "61ab2579215aa8a0024a2f9368fc1298fdecfd18" - run: ./gradlew jacocoTestReport sonarqube --stacktrace -i + run: ./gradlew jacocoTestReport sonar --stacktrace -i # Code format check code-format-check: diff --git a/.infra/checkstyle/import-control.xml b/.infra/checkstyle/import-control.xml index 226b49e4b..ec1d6da5d 100644 --- a/.infra/checkstyle/import-control.xml +++ b/.infra/checkstyle/import-control.xml @@ -5,6 +5,7 @@ + diff --git a/build.gradle.kts b/build.gradle.kts index 66e9b0d94..607edf1bf 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -304,8 +304,7 @@ tasks { javadoc { if (releaseBuild) { javadocTool.set(project.javaToolchains.javadocToolFor { - // create Javadoc with least Java version to get all features - // (e.g. search result page on 20) + // create Javadoc with the minimum Java version needed for our desired features (e.g. search) languageVersion.set(JavaLanguageVersion.of(21)) }) } diff --git a/src/demo/java/org/junitpioneer/jupiter/DisableIfTestFailsExtensionDemo.java b/src/demo/java/org/junitpioneer/jupiter/DisableIfTestFailsExtensionDemo.java index 97fc16459..ff0d4829d 100644 --- a/src/demo/java/org/junitpioneer/jupiter/DisableIfTestFailsExtensionDemo.java +++ b/src/demo/java/org/junitpioneer/jupiter/DisableIfTestFailsExtensionDemo.java @@ -10,8 +10,8 @@ package org.junitpioneer.jupiter; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.io.IOException; @@ -38,7 +38,7 @@ void test1() { @Test @Order(2) void test2() { - fail(); + fail("fails"); } @Test @@ -64,7 +64,7 @@ void test1() { @Order(2) void test2() { // fails test with assertion - assertTrue(false); + assertThat(false).isTrue(); } @Test diff --git a/src/demo/java/org/junitpioneer/jupiter/ExpectedToFailExtensionDemo.java b/src/demo/java/org/junitpioneer/jupiter/ExpectedToFailExtensionDemo.java index 22afe9747..0477375d7 100644 --- a/src/demo/java/org/junitpioneer/jupiter/ExpectedToFailExtensionDemo.java +++ b/src/demo/java/org/junitpioneer/jupiter/ExpectedToFailExtensionDemo.java @@ -10,7 +10,7 @@ package org.junitpioneer.jupiter; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; @@ -21,7 +21,7 @@ public class ExpectedToFailExtensionDemo { @ExpectedToFail void test() { int actual = brokenMethod(); - assertEquals(10, actual); + assertThat(actual).isEqualTo(10); } // end::expected_to_fail[] @@ -30,7 +30,7 @@ void test() { @ExpectedToFail("Implementation bug in brokenMethod()") void doSomething() { int actual = brokenMethod(); - assertEquals(10, actual); + assertThat(actual).isEqualTo(10); } // end::expected_to_fail_message[] diff --git a/src/demo/java/org/junitpioneer/jupiter/StdInOutExtensionDemo.java b/src/demo/java/org/junitpioneer/jupiter/StdInOutExtensionDemo.java index 5a52d21d5..7e3fa304d 100644 --- a/src/demo/java/org/junitpioneer/jupiter/StdInOutExtensionDemo.java +++ b/src/demo/java/org/junitpioneer/jupiter/StdInOutExtensionDemo.java @@ -101,10 +101,10 @@ void testReadLines(StdIn in) throws IOException { String[] lines = in.capturedLines(); // This is failing - // assertEquals(lines, "line1", "line2"); + // assertThat(lines).containsExactly("line1", "line2"); // This is passing - // assertEquals(lines, "line1", "line2", "line3"); + // assertThat(lines).containsExactly("line1", "line2", "line3"); } } diff --git a/src/demo/java/org/junitpioneer/jupiter/cartesian/BitArgumentProvider.java b/src/demo/java/org/junitpioneer/jupiter/cartesian/BitArgumentProvider.java index c569c2bf3..8b9914239 100644 --- a/src/demo/java/org/junitpioneer/jupiter/cartesian/BitArgumentProvider.java +++ b/src/demo/java/org/junitpioneer/jupiter/cartesian/BitArgumentProvider.java @@ -17,6 +17,7 @@ import org.junit.jupiter.api.extension.ExtensionContext; +// implementation example, does not contain tests public class BitArgumentProvider { // tag::cartesian_bit_source_annotation[] diff --git a/src/demo/java/org/junitpioneer/jupiter/cartesian/CartesianTestExtensionDemo.java b/src/demo/java/org/junitpioneer/jupiter/cartesian/CartesianTestExtensionDemo.java index d747b2c54..ed8f36aa1 100644 --- a/src/demo/java/org/junitpioneer/jupiter/cartesian/CartesianTestExtensionDemo.java +++ b/src/demo/java/org/junitpioneer/jupiter/cartesian/CartesianTestExtensionDemo.java @@ -23,6 +23,7 @@ import java.time.temporal.TemporalUnit; import java.util.Arrays; import java.util.EnumSet; +import java.util.Map; import java.util.Objects; import java.util.concurrent.TimeUnit; import java.util.function.Predicate; @@ -178,6 +179,7 @@ static ArgumentSets stringIntFactory() { } // end::cartesian_argument_sets_reuse[] + // these tests fail intentionally ~> no @Nested static class MisconfiguredExamples { // tag::cartesian_bad_examples[] @@ -236,7 +238,7 @@ static ArgumentSets resolveTestReporterParam() { // tag::cartesian_argument_sets_int_argument_provider[] class IntArgumentsProvider - implements CartesianParameterArgumentsProvider { + implements CartesianParameterArgumentsProvider { @Override public Stream provideArguments( @@ -282,5 +284,13 @@ ArgumentSets provideArguments() { } // end::cartesian_argument_sets_with_non_static_factory[] + static class MyTestReporter implements TestReporter { + + @Override + public void publishEntry(Map map) { + } + + } + } // @formatter:on diff --git a/src/demo/java/org/junitpioneer/jupiter/cartesian/MyTestReporter.java b/src/demo/java/org/junitpioneer/jupiter/cartesian/MyTestReporter.java deleted file mode 100644 index 615398682..000000000 --- a/src/demo/java/org/junitpioneer/jupiter/cartesian/MyTestReporter.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright 2016-2023 the original author or authors. - * - * All rights reserved. This program and the accompanying materials are - * made available under the terms of the Eclipse Public License v2.0 which - * accompanies this distribution and is available at - * - * http://www.eclipse.org/legal/epl-v20.html - */ - -package org.junitpioneer.jupiter.cartesian; - -import java.util.Map; - -import org.junit.jupiter.api.TestReporter; - -public class MyTestReporter implements TestReporter { - - @Override - public void publishEntry(Map map) { - - } - -} diff --git a/src/demo/java/org/junitpioneer/jupiter/cartesian/NumberArgumentProvider.java b/src/demo/java/org/junitpioneer/jupiter/cartesian/NumberArgumentProvider.java index 2869159ec..182da3915 100644 --- a/src/demo/java/org/junitpioneer/jupiter/cartesian/NumberArgumentProvider.java +++ b/src/demo/java/org/junitpioneer/jupiter/cartesian/NumberArgumentProvider.java @@ -19,6 +19,7 @@ import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.params.support.AnnotationConsumer; +// implementation example, does not contain tests public class NumberArgumentProvider { // tag::cartesian_number_argument_provider[] @@ -31,7 +32,7 @@ public class NumberArgumentProvider { } - class NumberArgumentsProvider implements CartesianMethodArgumentsProvider, AnnotationConsumer { + static class NumberArgumentsProvider implements CartesianMethodArgumentsProvider, AnnotationConsumer { private int[] numbers; diff --git a/src/demo/java/org/junitpioneer/jupiter/cartesian/PeopleProviderSources.java b/src/demo/java/org/junitpioneer/jupiter/cartesian/PeopleProviderSources.java index f00e5ba01..e4ede259e 100644 --- a/src/demo/java/org/junitpioneer/jupiter/cartesian/PeopleProviderSources.java +++ b/src/demo/java/org/junitpioneer/jupiter/cartesian/PeopleProviderSources.java @@ -22,6 +22,7 @@ import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.params.support.AnnotationConsumer; +// implementation example, does not contain tests public class PeopleProviderSources { // tag::cartesian_people_provider_with_CartesianParameterArgumentsProvider[] @@ -36,7 +37,7 @@ public class PeopleProviderSources { } - class PeopleProvider implements CartesianParameterArgumentsProvider { + class PeopleProvider implements CartesianParameterArgumentsProvider { @Override public Stream provideArguments(ExtensionContext context, Parameter parameter) { @@ -49,7 +50,7 @@ public Stream provideArguments(ExtensionContext context, Parameter param } // end::cartesian_people_provider_with_CartesianParameterArgumentsProvider[] - class Person { + static class Person { String name; int age; @@ -63,7 +64,7 @@ public Person(String name, int age) { // tag::cartesian_people_provider_with_AnnotationConsumer[] class PeopleProviderWithAnnotationConsumer - implements CartesianParameterArgumentsProvider, AnnotationConsumer { + implements CartesianParameterArgumentsProvider, AnnotationConsumer { private People source; diff --git a/src/demo/java/org/junitpioneer/jupiter/params/DisableParameterizedExtensionDemo.java b/src/demo/java/org/junitpioneer/jupiter/params/DisableParameterizedExtensionDemo.java index aeb61c38f..490e7e486 100644 --- a/src/demo/java/org/junitpioneer/jupiter/params/DisableParameterizedExtensionDemo.java +++ b/src/demo/java/org/junitpioneer/jupiter/params/DisableParameterizedExtensionDemo.java @@ -10,7 +10,7 @@ package org.junitpioneer.jupiter.params; -import static org.junit.jupiter.api.Assertions.fail; +import static org.assertj.core.api.Assertions.fail; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; diff --git a/src/demo/java/org/junitpioneer/jupiter/resource/InMemoryDirectory.java b/src/demo/java/org/junitpioneer/jupiter/resource/InMemoryDirectory.java index 611b2e050..92657e375 100644 --- a/src/demo/java/org/junitpioneer/jupiter/resource/InMemoryDirectory.java +++ b/src/demo/java/org/junitpioneer/jupiter/resource/InMemoryDirectory.java @@ -23,8 +23,8 @@ import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; +// implementation example, does not contain tests // tag::in_memory_directory[] - public final class InMemoryDirectory implements ResourceFactory { private static final AtomicInteger DIRECTORY_NAME = new AtomicInteger(); @@ -42,16 +42,16 @@ public Resource create(List arguments) throws Exception { Path newInMemoryDirectory = this.fileSystem.getPath("/" + directoryPrefix + DIRECTORY_NAME.getAndIncrement()); Files.createDirectory(newInMemoryDirectory); - return new Resource() { + return new Resource<>() { @Override - public Path get() throws Exception { + public Path get() { return newInMemoryDirectory; } @Override public void close() throws Exception { - Files.walkFileTree(newInMemoryDirectory, new SimpleFileVisitor() { + Files.walkFileTree(newInMemoryDirectory, new SimpleFileVisitor<>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { diff --git a/src/demo/java/org/junitpioneer/jupiter/resource/ResourceExtensionDemo.java b/src/demo/java/org/junitpioneer/jupiter/resource/ResourceExtensionDemo.java index 021aef57f..280b5093d 100644 --- a/src/demo/java/org/junitpioneer/jupiter/resource/ResourceExtensionDemo.java +++ b/src/demo/java/org/junitpioneer/jupiter/resource/ResourceExtensionDemo.java @@ -10,12 +10,12 @@ package org.junitpioneer.jupiter.resource; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; -import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; public class ResourceExtensionDemo { @@ -24,7 +24,7 @@ public class ResourceExtensionDemo { @Test void test1(@New(TemporaryDirectory.class) Path tempDir) { // Test code goes here, e.g., - assertTrue(Files.exists(tempDir)); + assertThat(tempDir).exists(); } @Test @@ -37,7 +37,7 @@ void test2(@New(TemporaryDirectory.class) Path tempDir) { @Test void dirTest1(@Dir Path tempDir) { // Test code goes here, e.g., - assertTrue(Files.exists(tempDir)); + assertThat(tempDir).exists(); } @Test @@ -54,7 +54,7 @@ void testWithArg( Path tempDir) { // Test code goes here, e.g., Path rootTempDir = Paths.get(System.getProperty("java.io.tmpdir")); - assertTrue(rootTempDir.relativize(tempDir).toString().startsWith("customPrefix")); + assertThat(rootTempDir.relativize(tempDir)).asString().startsWith("customPrefix"); } // end::create_new_resource_with_arg_demo[] // @formatter:on @@ -66,7 +66,7 @@ void sharedResourceTest1( @Shared(factory = TemporaryDirectory.class, name = "sharedTempDir") Path sharedTempDir) { // Test code goes here, e.g., - assertTrue(Files.exists(sharedTempDir)); + assertThat(sharedTempDir).exists(); } @Test @@ -105,40 +105,42 @@ void secondSharedResource( // end::create_multiple_shared_resources_demo[] // @formatter:on -} - -// @formatter:off -// tag::create_global_shared_resource_demo_first[] -class FirstTest { + @Nested + // @formatter:off + // tag::create_global_shared_resource_demo_first[] + class FirstTest { + + @Test + void test( + @Shared( + factory = TemporaryDirectory.class, + name = "globalTempDir", + scope = Shared.Scope.GLOBAL) + Path tempDir) { + // Test code using the global shared resource... + } - @Test - void test( - @Shared( - factory = TemporaryDirectory.class, - name = "globalTempDir", - scope = Shared.Scope.GLOBAL) - Path tempDir) { - // Test code using the global shared resource... } + // end::create_global_shared_resource_demo_first[] + // @formatter:on -} -// end::create_global_shared_resource_demo_first[] -// @formatter:on - -// @formatter:off -// tag::create_global_shared_resource_demo_second[] -class SecondTest { + @Nested + // @formatter:off + // tag::create_global_shared_resource_demo_second[] + class SecondTest { + + @Test + void test( + @Shared( + factory = TemporaryDirectory.class, + name = "globalTempDir", + scope = Shared.Scope.GLOBAL) + Path tempDir) { + // Test code using the global shared resource... + } - @Test - void test( - @Shared( - factory = TemporaryDirectory.class, - name = "globalTempDir", - scope = Shared.Scope.GLOBAL) - Path tempDir) { - // Test code using the global shared resource... } + // end::create_global_shared_resource_demo_second[] + // @formatter:on } -// end::create_global_shared_resource_demo_second[] -// @formatter:on diff --git a/src/main/java/org/junitpioneer/internal/PioneerPreconditions.java b/src/main/java/org/junitpioneer/internal/PioneerPreconditions.java index afdb8a3e9..d3ba0b3c2 100644 --- a/src/main/java/org/junitpioneer/internal/PioneerPreconditions.java +++ b/src/main/java/org/junitpioneer/internal/PioneerPreconditions.java @@ -32,11 +32,7 @@ private PioneerPreconditions() { * @return the supplied string */ public static String notBlank(String str, String message) { - if (str == null || str.isBlank()) { - throw new PreconditionViolationException(message); - } - - return str; + return notBlank(str, () -> message); } /** @@ -60,10 +56,7 @@ public static String notBlank(String str, Supplier messageSupplier) { * @return the supplied object */ public static T notNull(T object, String message) { - if (object == null) { - throw new PreconditionViolationException(message); - } - return object; + return notNull(object, () -> message); } /** @@ -86,10 +79,7 @@ public static T notNull(T object, Supplier messageSupplier) { * @return the supplied string */ public static > T notEmpty(T collection, String message) { - if (collection == null || collection.isEmpty()) { - throw new PreconditionViolationException(message); - } - return collection; + return notEmpty(collection, () -> message); } /** diff --git a/src/main/java/org/junitpioneer/jupiter/ExpectedToFailExtension.java b/src/main/java/org/junitpioneer/jupiter/ExpectedToFailExtension.java index 6e4091ed3..0e13a5cf3 100644 --- a/src/main/java/org/junitpioneer/jupiter/ExpectedToFailExtension.java +++ b/src/main/java/org/junitpioneer/jupiter/ExpectedToFailExtension.java @@ -10,8 +10,6 @@ package org.junitpioneer.jupiter; -import static org.junit.jupiter.api.Assertions.fail; - import java.lang.reflect.Method; import org.junit.jupiter.api.extension.Extension; @@ -19,6 +17,7 @@ import org.junit.jupiter.api.extension.InvocationInterceptor; import org.junit.jupiter.api.extension.ReflectiveInvocationContext; import org.junit.platform.commons.support.AnnotationSupport; +import org.opentest4j.AssertionFailedError; import org.opentest4j.TestAbortedException; class ExpectedToFailExtension implements Extension, InvocationInterceptor { @@ -50,7 +49,7 @@ private static void invokeAndInvertResult(Invocation invocation, Extension throw new TestAbortedException(message, t); } - fail("Test marked as 'expected to fail' succeeded; remove @ExpectedToFail from it"); + throw new AssertionFailedError("Test marked as 'expected to fail' succeeded; remove @ExpectedToFail from it"); } /** diff --git a/src/main/java/org/junitpioneer/jupiter/resource/ResourceExtension.java b/src/main/java/org/junitpioneer/jupiter/resource/ResourceExtension.java index f3eaab61c..cc70cc814 100644 --- a/src/main/java/org/junitpioneer/jupiter/resource/ResourceExtension.java +++ b/src/main/java/org/junitpioneer/jupiter/resource/ResourceExtension.java @@ -10,6 +10,7 @@ package org.junitpioneer.jupiter.resource; +import static java.lang.String.format; import static java.util.Comparator.comparing; import static java.util.stream.Collectors.toUnmodifiableList; @@ -50,7 +51,7 @@ public boolean supportsParameter(ParameterContext parameterContext, ExtensionCon if (parameterContext.isAnnotated(New.class) && parameterContext.isAnnotated(Shared.class)) { // @formatter:off String message = - String.format( + format( "Parameter [%s] in %s is annotated with both @New and @Shared", parameterContext.getParameter(), testMethodDescription(extensionContext)); // @formatter:on @@ -79,7 +80,7 @@ public Object resolveParameter(ParameterContext parameterContext, ExtensionConte } // @formatter:off - String message = String.format( + String message = format( "Parameter [%s] in %s is not annotated with @New or @Shared", parameterContext.getParameter(), testMethodDescription(extensionContext)); // @formatter:on @@ -88,7 +89,7 @@ public Object resolveParameter(ParameterContext parameterContext, ExtensionConte private T checkType(Object resource, Class type) { if (!type.isInstance(resource)) { - String message = String.format("Parameter [%s] is not of the correct target type %s", resource, type); + String message = format("Parameter [%s] is not of the correct target type %s", resource, type); throw new ParameterResolutionException(message); } return type.cast(resource); @@ -107,7 +108,7 @@ private Object resolveNew(New newAnnotation, ExtensionContext.Store store) { } catch (Exception ex) { // @formatter:off - String message = String.format( + String message = format( "Unable to get the contents of the resource created by `%s`", resourceFactory.getClass().getTypeName()); // @formatter:on @@ -116,7 +117,7 @@ private Object resolveNew(New newAnnotation, ExtensionContext.Store store) { if (result == null) { // @formatter:off - String message = String.format( + String message = format( "The resource returned by [%s] was null, which is not allowed", getMethod(resource.getClass(), "get")); // @formatter:on @@ -153,7 +154,7 @@ private Object resolveShared(Shared sharedAnnotation, Parameter[] parameters, Ex } catch (Exception ex) { // @formatter:off - String message = String.format( + String message = format( "Unable to get the contents of the resource created by `%s`", sharedAnnotation.factory()); // @formatter:on @@ -162,7 +163,7 @@ private Object resolveShared(Shared sharedAnnotation, Parameter[] parameters, Ex if (result == null) { // @formatter:off - String message = String.format( + String message = format( "The resource returned by [%s] was null, which is not allowed", getMethod(resource.getClass(), "get")); // @formatter:on @@ -190,13 +191,13 @@ private Resource newResource(Object newOrSharedAnnotation, ResourceFactory } catch (Exception ex) { String message = // - String.format("Unable to create a resource from `%s`", resourceFactory.getClass().getTypeName()); + format("Unable to create a resource from `%s`", resourceFactory.getClass().getTypeName()); throw new ParameterResolutionException(message, ex); } if (result == null) { // @formatter:off - String message = String.format( + String message = format( "The `Resource` instance returned by the factory method [%s] with arguments %s was null, which is not allowed", getMethod(resourceFactory.getClass(), "create", List.class), arguments); @@ -222,7 +223,7 @@ private void throwIfHasAnnotationWithSameNameButDifferentType(ExtensionContext.S && !sharedAnnotation.factory().equals(presentResourceFactory.getClass())) { // @formatter:off String message = - String.format( + format( "Two or more parameters are annotated with @Shared annotations with the name \"%s\" " + "but with different factory classes", sharedAnnotation.name()); @@ -244,7 +245,7 @@ private void throwIfHasAnnotationWithSameNameButDifferentScope(ExtensionContext. && !presentSharedAnnotation.scope().equals(sharedAnnotation.scope())) { // @formatter:off String message = - String.format( + format( "Two or more parameters are annotated with @Shared annotations with the name " + "\"%s\" but with different scopes", sharedAnnotation.name()); @@ -260,7 +261,7 @@ private void throwIfMultipleParametersHaveExactAnnotation(Parameter[] parameters if (parameterCount > 1) { // @formatter:off String message = - String.format( + format( "A test method has %d parameters annotated with @Shared with the same factory type " + "and name; this is redundant, so it is not allowed", parameterCount); @@ -306,13 +307,10 @@ private String testMethodDescription(ExtensionContext extensionContext) { } private Method getMethod(Class clazz, String method, Class... parameterTypes) { - try { - return clazz.getMethod(method, parameterTypes); - } - catch (NoSuchMethodException e) { - throw new IllegalStateException( - String.format("There should be a `%s` method on class `%s`", method, clazz.getTypeName()), e); - } + return ReflectionSupport + .findMethod(clazz, method, parameterTypes) + .orElseThrow(() -> new IllegalStateException( + format("There should be a `%s` method on class `%s`", method, clazz.getTypeName()))); } @Override @@ -463,13 +461,10 @@ private void putNewLockForShared(Shared shared, ExtensionContext.Store store) { } private ReentrantLock findLockForShared(Shared shared, ExtensionContext.Store store) { - // @formatter:off - return Optional.ofNullable(store.get(resourceLockKey(shared), ReentrantLock.class)) - .orElseThrow(() -> { - String message = String.format("There should be a shared resource for the name %s", shared.name()); - return new IllegalStateException(message); - }); - // @formatter:on + return Optional + .ofNullable(store.get(resourceLockKey(shared), ReentrantLock.class)) + .orElseThrow(() -> new IllegalStateException( + format("There should be a shared resource for the name %s", shared.name()))); } private T invokeWithLocks(Invocation invocation, List locks) throws Throwable { diff --git a/src/test/java/org/junitpioneer/jupiter/DisableIfTestFailsTests.java b/src/test/java/org/junitpioneer/jupiter/DisableIfTestFailsTests.java index 324090f67..0c279fd56 100644 --- a/src/test/java/org/junitpioneer/jupiter/DisableIfTestFailsTests.java +++ b/src/test/java/org/junitpioneer/jupiter/DisableIfTestFailsTests.java @@ -10,7 +10,7 @@ package org.junitpioneer.jupiter; -import static org.junit.jupiter.api.Assertions.fail; +import static org.assertj.core.api.Assertions.fail; import static org.junit.jupiter.api.parallel.ExecutionMode.SAME_THREAD; import static org.junitpioneer.testkit.PioneerTestKit.abort; import static org.junitpioneer.testkit.assertion.PioneerAssert.assertThat; @@ -153,7 +153,7 @@ void test1() { @Test @Order(2) void test2() { - fail(); + fail(""); } @Test @@ -176,7 +176,7 @@ void test1() { @Order(2) void test2() { // fail test with assertion - fail(); + fail(""); } @Test diff --git a/src/test/java/org/junitpioneer/jupiter/ExpectedToFailExtensionTests.java b/src/test/java/org/junitpioneer/jupiter/ExpectedToFailExtensionTests.java index e518835b8..3b0720d5a 100644 --- a/src/test/java/org/junitpioneer/jupiter/ExpectedToFailExtensionTests.java +++ b/src/test/java/org/junitpioneer/jupiter/ExpectedToFailExtensionTests.java @@ -12,7 +12,7 @@ import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; -import static org.junit.jupiter.api.Assertions.fail; +import static org.assertj.core.api.Assertions.fail; import static org.junitpioneer.testkit.assertion.PioneerAssert.assertThat; import java.lang.annotation.Retention; @@ -28,7 +28,6 @@ import org.junit.jupiter.api.Test; import org.junitpioneer.testkit.ExecutionResults; import org.junitpioneer.testkit.PioneerTestKit; -import org.opentest4j.AssertionFailedError; import org.opentest4j.TestAbortedException; @DisplayName("ExpectedToFail extension") @@ -42,7 +41,7 @@ void abortsOnTestFailure() { .whichAborted() .withExceptionInstanceOf(TestAbortedException.class) .hasMessage("Test marked as temporarily 'expected to fail' failed as expected") - .hasCause(new AssertionFailedError("failed")); + .hasCause(new AssertionError("failed")); } @Test @@ -54,7 +53,7 @@ void abortsOnTestFailureWithMetaAnnotation() { .whichAborted() .withExceptionInstanceOf(TestAbortedException.class) .hasMessage("Test marked as temporarily 'expected to fail' failed as expected") - .hasCause(new AssertionFailedError("failed")); + .hasCause(new AssertionError("failed")); } @Test @@ -66,7 +65,7 @@ void abortsOnTestFailureWithMessage() { .whichAborted() .withExceptionInstanceOf(TestAbortedException.class) .hasMessage("Custom message") - .hasCause(new AssertionFailedError("failed")); + .hasCause(new AssertionError("failed")); } @Test @@ -120,7 +119,7 @@ void doesNotAbortOnAfterEachTestFailure() { .withExceptionInstanceOf(AssertionError.class) .hasMessage("Test marked as 'expected to fail' succeeded; remove @ExpectedToFail from it") // Note: This check for suppressed exception actually tests JUnit platform behavior - .hasSuppressedException(new AssertionFailedError("after each")); + .hasSuppressedException(new AssertionError("after each")); } @Test @@ -142,7 +141,7 @@ void afterEachAbortAfterTestFailure() { .whichAborted() .withExceptionInstanceOf(TestAbortedException.class) .hasMessage("Test marked as temporarily 'expected to fail' failed as expected") - .hasCause(new AssertionFailedError("failed")) + .hasCause(new AssertionError("failed")) // Note: This check for suppressed exception actually tests JUnit platform behavior .has(new Condition<>((Throwable throwable) -> { Throwable[] suppressed = throwable.getSuppressed(); diff --git a/src/test/java/org/junitpioneer/jupiter/ReportEntryExtensionTests.java b/src/test/java/org/junitpioneer/jupiter/ReportEntryExtensionTests.java index db1c7f80a..f3a688078 100644 --- a/src/test/java/org/junitpioneer/jupiter/ReportEntryExtensionTests.java +++ b/src/test/java/org/junitpioneer/jupiter/ReportEntryExtensionTests.java @@ -10,7 +10,7 @@ package org.junitpioneer.jupiter; -import static org.junit.jupiter.api.Assertions.fail; +import static org.assertj.core.api.Assertions.fail; import static org.junitpioneer.jupiter.ReportEntry.PublishCondition.ALWAYS; import static org.junitpioneer.jupiter.ReportEntry.PublishCondition.ON_ABORTED; import static org.junitpioneer.jupiter.ReportEntry.PublishCondition.ON_FAILURE; @@ -464,7 +464,7 @@ void always_success() { @Test @ReportEntry(value = "'Tapping at my chamber door' -", when = ALWAYS) void always_failure() { - fail(); + fail(""); } @Test @@ -487,7 +487,7 @@ void onSuccess_success() { @Test @ReportEntry(value = "And each separate dying ember wrought its ghost upon the floor.", when = ON_SUCCESS) void onSuccess_failure() { - fail(); + fail(""); } @Test @@ -510,7 +510,7 @@ void onFailure_success() { @Test @ReportEntry(value = "Nameless here for evermore.", when = ON_FAILURE) void onFailure_failure() { - fail(); + fail(""); } @Test @@ -533,7 +533,7 @@ void onAborted_success() { @Test @ReportEntry(value = "Tis some visitor entreating entrance at my chamber door—", when = ON_ABORTED) void onAborted_failure() { - fail(); + fail(""); } @Test @@ -562,7 +562,7 @@ void repeated_success() { @ReportEntry(value = "murmured back the word, “Lenore!”—", when = ON_FAILURE) @ReportEntry(value = "Merely this and nothing more.", when = ON_ABORTED) void repeated_failure() { - fail(); + fail(""); } @Test diff --git a/src/test/java/org/junitpioneer/jupiter/issue/IssueExtensionExecutionListenerTests.java b/src/test/java/org/junitpioneer/jupiter/issue/IssueExtensionExecutionListenerTests.java index 3a92f8754..a288cb8b8 100644 --- a/src/test/java/org/junitpioneer/jupiter/issue/IssueExtensionExecutionListenerTests.java +++ b/src/test/java/org/junitpioneer/jupiter/issue/IssueExtensionExecutionListenerTests.java @@ -11,7 +11,6 @@ package org.junitpioneer.jupiter.issue; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertAll; import static org.junitpioneer.jupiter.issue.IssueExtensionExecutionListener.REPORT_ENTRY_KEY; import static org.junitpioneer.jupiter.issue.IssueExtensionExecutionListener.TIME_REPORT_KEY; import static org.junitpioneer.jupiter.issue.TestPlanHelper.createTestIdentifier; @@ -67,8 +66,8 @@ void issueTestCasesCreated() { assertThat(allTests.size()).isEqualTo(1); IssueTestSuite issueTestSuite = allTests.get(0); - assertAll(() -> assertThat(issueTestSuite.issueId()).isEqualTo("#123"), - () -> assertThat(issueTestSuite.tests().size()).isEqualTo(1)); + assertThat(issueTestSuite.issueId()).isEqualTo("#123"); + assertThat(issueTestSuite.tests()).hasSize(1); assertThat(issueTestSuite.tests()) .containsExactly(new IssueTestCase("[test:successful-test]", Status.SUCCESSFUL, 6L)); @@ -90,8 +89,8 @@ void abortedIssueTestCaseCreated() { assertThat(allTests.size()).isEqualTo(1); IssueTestSuite issueTestSuite = allTests.get(0); - assertAll(() -> assertThat(issueTestSuite.issueId()).isEqualTo("#123"), - () -> assertThat(issueTestSuite.tests().size()).isEqualTo(1)); + assertThat(issueTestSuite.issueId()).isEqualTo("#123"); + assertThat(issueTestSuite.tests()).hasSize(1); assertThat(issueTestSuite.tests()).containsExactly(new IssueTestCase("[test:aborted-test]", Status.ABORTED)); } @@ -116,8 +115,8 @@ void multipleIssueTestCasesCreated() { assertThat(allTests.size()).isEqualTo(1); IssueTestSuite issueTestSuite = allTests.get(0); - assertAll(() -> assertThat(issueTestSuite.issueId()).isEqualTo("#123"), - () -> assertThat(issueTestSuite.tests().size()).isEqualTo(2)); + assertThat(issueTestSuite.issueId()).isEqualTo("#123"); + assertThat(issueTestSuite.tests()).hasSize(2); assertThat(issueTestSuite.tests()) .containsExactlyInAnyOrder(new IssueTestCase("[test:successful-test]", Status.SUCCESSFUL), diff --git a/src/test/java/org/junitpioneer/jupiter/params/DisabledIfNameExtensionTests.java b/src/test/java/org/junitpioneer/jupiter/params/DisabledIfNameExtensionTests.java index 3aa508433..aec2eb0a8 100644 --- a/src/test/java/org/junitpioneer/jupiter/params/DisabledIfNameExtensionTests.java +++ b/src/test/java/org/junitpioneer/jupiter/params/DisabledIfNameExtensionTests.java @@ -10,7 +10,7 @@ package org.junitpioneer.jupiter.params; -import static org.junit.jupiter.api.Assertions.fail; +import static org.assertj.core.api.Assertions.fail; import static org.junitpioneer.testkit.assertion.PioneerAssert.assertThat; import java.util.Arrays; diff --git a/src/test/java/org/junitpioneer/jupiter/resource/PathDeleterTests.java b/src/test/java/org/junitpioneer/jupiter/resource/PathDeleterTests.java index 86253521f..af9c1bee6 100644 --- a/src/test/java/org/junitpioneer/jupiter/resource/PathDeleterTests.java +++ b/src/test/java/org/junitpioneer/jupiter/resource/PathDeleterTests.java @@ -11,7 +11,7 @@ package org.junitpioneer.jupiter.resource; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.assertj.core.api.Assertions.assertThatCode; import java.io.IOException; import java.nio.file.FileSystem; @@ -40,8 +40,9 @@ void deletesFile() throws IOException { @Test void deletingNonExistentFileProducesNoIOException() throws IOException { try (FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix())) { - assertDoesNotThrow( - () -> PathDeleter.INSTANCE.visitFile(fileSystem.getPath("some", "arbitrary", "file.txt"), null)); + assertThatCode( + () -> PathDeleter.INSTANCE.visitFile(fileSystem.getPath("some", "arbitrary", "file.txt"), null)) + .doesNotThrowAnyException(); } } @@ -75,8 +76,9 @@ void deletesNonEmptyDirectory() throws IOException { @Test void deletingNonExistentDirectoryProducesNoIOException() throws IOException { try (FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix())) { - assertDoesNotThrow(() -> PathDeleter.INSTANCE - .postVisitDirectory(fileSystem.getPath("some", "arbitrary", "directory"), null)); + assertThatCode(() -> PathDeleter.INSTANCE + .postVisitDirectory(fileSystem.getPath("some", "arbitrary", "directory"), null)) + .doesNotThrowAnyException(); } } diff --git a/src/test/java/org/junitpioneer/jupiter/resource/ResourcesTests.java b/src/test/java/org/junitpioneer/jupiter/resource/ResourcesTests.java index 02371a806..0fbe7eeff 100644 --- a/src/test/java/org/junitpioneer/jupiter/resource/ResourcesTests.java +++ b/src/test/java/org/junitpioneer/jupiter/resource/ResourcesTests.java @@ -10,14 +10,10 @@ package org.junitpioneer.jupiter.resource; -import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.fail; -import static org.junit.platform.testkit.engine.EventConditions.finished; -import static org.junit.platform.testkit.engine.TestExecutionResultConditions.cause; -import static org.junit.platform.testkit.engine.TestExecutionResultConditions.instanceOf; -import static org.junit.platform.testkit.engine.TestExecutionResultConditions.message; -import static org.junit.platform.testkit.engine.TestExecutionResultConditions.throwable; +import static org.assertj.core.api.Assertions.fail; +import static org.junitpioneer.testkit.PioneerTestKit.executeTestClass; +import static org.junitpioneer.testkit.PioneerTestKit.executeTestClasses; import static org.junitpioneer.testkit.assertion.PioneerAssert.assertThat; import java.io.IOException; @@ -31,7 +27,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ParameterResolutionException; import org.junitpioneer.testkit.ExecutionResults; -import org.junitpioneer.testkit.PioneerTestKit; @DisplayName("Resources extension") class ResourcesTests { @@ -43,9 +38,9 @@ class WhenNewResourceFactoryAppliedToParameterTests { @DisplayName("then ::create is called") @Test void thenCreateIsCalled() { - ExecutionResults executionResults = PioneerTestKit - .executeTestClass(CountingResourceFactory1TestCases.class); - assertThat(executionResults.testEvents().debug().succeeded().count()).isEqualTo(1); + ExecutionResults results = executeTestClass(CountingResourceFactory1TestCases.class); + + assertThat(results).hasSingleSucceededTest(); assertThat(CountingResourceFactory1.createCalls).isEqualTo(1); } @@ -56,21 +51,16 @@ class AndFactoryThrowsOnCreateTests { @DisplayName("then the thrown exception is wrapped and propagated") @Test void thenThrownExceptionIsWrappedAndPropagated() { - ExecutionResults executionResults = PioneerTestKit.executeTestClass(ThrowOnNewRFCreateTestCases.class); - executionResults - .allEvents() - .debug() - .assertThatEvents() - .haveExactly( // - 1, // - finished( // - throwable( // - instanceOf(ParameterResolutionException.class), // - message("Unable to create a resource from `" - + ThrowOnRFCreateResourceFactory.class.getTypeName() + "`"), // - cause( // - instanceOf(EXPECTED_THROW_ON_RF_CREATE_EXCEPTION.getClass()), // - message(EXPECTED_THROW_ON_RF_CREATE_EXCEPTION.getMessage()))))); + ExecutionResults results = executeTestClass(ThrowOnNewRFCreateTestCases.class); + + assertThat(results) + .hasSingleFailedTest() + .withExceptionInstanceOf(ParameterResolutionException.class) + .hasMessage("Unable to create a resource from `" + + ThrowOnRFCreateResourceFactory.class.getTypeName() + "`") + .cause() + .isInstanceOf(EXPECTED_THROW_ON_RF_CREATE_EXCEPTION.getClass()) + .hasMessage(EXPECTED_THROW_ON_RF_CREATE_EXCEPTION.getMessage()); } } @@ -82,17 +72,12 @@ class AndFactoryThrowsOnCloseTests { @DisplayName("then the thrown exception is propagated") @Test void thenThrownExceptionIsPropagated() { - ExecutionResults executionResults = PioneerTestKit.executeTestClass(ThrowOnNewRFCloseTestCases.class); - executionResults - .allEvents() - .debug() - .assertThatEvents() - .haveExactly( // - 1, // - finished( // - throwable( // - instanceOf(EXPECTED_THROW_ON_RF_CLOSE_EXCEPTION.getClass()), // - message(EXPECTED_THROW_ON_RF_CLOSE_EXCEPTION.getMessage())))); + ExecutionResults results = executeTestClass(ThrowOnNewRFCloseTestCases.class); + + assertThat(results) + .hasSingleFailedTest() + .withExceptionInstanceOf(EXPECTED_THROW_ON_RF_CLOSE_EXCEPTION.getClass()) + .hasMessage(EXPECTED_THROW_ON_RF_CLOSE_EXCEPTION.getMessage()); } } @@ -104,18 +89,12 @@ class AndFactoryReturnsNullOnCreateTests { @DisplayName("then a proper exception is thrown") @Test void thenProperExceptionIsThrown() { - ExecutionResults executionResults = PioneerTestKit - .executeTestClass(NewRFCreateReturnsNullTestCases.class); - executionResults - .allEvents() - .debug() - .assertThatEvents() - .haveExactly( // - 1, // - finished( // - throwable( // - instanceOf(ParameterResolutionException.class), // - message(message -> message.matches(".*`Resource` instance.*was null.*"))))); + ExecutionResults results = executeTestClass(NewRFCreateReturnsNullTestCases.class); + + assertThat(results) + .hasSingleFailedTest() + .withExceptionInstanceOf(ParameterResolutionException.class) + .hasMessageMatching(".*`Resource` instance.*was null.*"); } } @@ -131,21 +110,16 @@ class AndResourceThrowsOnGetTests { @DisplayName("then the thrown exception is wrapped and propagated") @Test void thenThrownExceptionIsWrappedAndPropagated() { - ExecutionResults executionResults = PioneerTestKit.executeTestClass(ThrowOnNewRGetTestCases.class); - executionResults - .allEvents() - .debug() - .assertThatEvents() - .haveExactly( // - 1, // - finished( // - throwable( // - instanceOf(ParameterResolutionException.class), // - message("Unable to get the contents of the resource created by `" - + ThrowOnRGetResourceFactory.class.getTypeName() + "`"), // - cause( // - instanceOf(EXPECTED_THROW_ON_R_GET_EXCEPTION.getClass()), // - message(EXPECTED_THROW_ON_R_GET_EXCEPTION.getMessage()))))); + ExecutionResults results = executeTestClass(ThrowOnNewRGetTestCases.class); + + assertThat(results) + .hasSingleFailedTest() + .withExceptionInstanceOf(ParameterResolutionException.class) + .hasMessage("Unable to get the contents of the resource created by `" + + ThrowOnRGetResourceFactory.class.getTypeName() + "`") + .cause() + .isInstanceOf(EXPECTED_THROW_ON_R_GET_EXCEPTION.getClass()) + .hasMessage(EXPECTED_THROW_ON_R_GET_EXCEPTION.getMessage()); } } @@ -157,18 +131,12 @@ class AndResourceThrowsOnCloseTests { @DisplayName("then the thrown exception is propagated") @Test void thenThrownExceptionIsWrappedAndPropagated() { - ExecutionResults executionResults = PioneerTestKit - .executeTestClass(ThrowOnNewRCloseTestCases.class); - executionResults - .allEvents() - .debug() - .assertThatEvents() - .haveExactly( // - 1, // - finished( // - throwable( // - instanceOf(EXPECTED_THROW_ON_R_CLOSE_EXCEPTION.getClass()), // - message(EXPECTED_THROW_ON_R_CLOSE_EXCEPTION.getMessage())))); + ExecutionResults results = executeTestClass(ThrowOnNewRCloseTestCases.class); + + assertThat(results) + .hasSingleFailedTest() + .withExceptionInstanceOf(EXPECTED_THROW_ON_R_CLOSE_EXCEPTION.getClass()) + .hasMessage(EXPECTED_THROW_ON_R_CLOSE_EXCEPTION.getMessage()); } } @@ -180,18 +148,29 @@ class AndResourceReturnsNullOnGetTests { @DisplayName("then a proper exception is thrown") @Test void thenProperExceptionIsThrown() { - ExecutionResults executionResults = PioneerTestKit - .executeTestClass(NewRGetReturnsNullTestCases.class); - executionResults - .allEvents() - .debug() - .assertThatEvents() - .haveExactly( // - 1, // - finished( // - throwable( // - instanceOf(ParameterResolutionException.class), - message(message -> message.matches(".*resource.*was null.*"))))); + ExecutionResults results = executeTestClass(NewRGetReturnsNullTestCases.class); + + assertThat(results) + .hasSingleFailedTest() + .withExceptionInstanceOf(ParameterResolutionException.class) + .hasMessageMatching(".*resource.*was null.*"); + } + + } + + @DisplayName("and the resource returned can't be cast to the parameter type") + @Nested + class AndResourceReturnedIsNotOfCorrectTypeTests { + + @DisplayName("then a proper exception is thrown") + @Test + void thenProperExceptionIsThrown() { + ExecutionResults results = executeTestClass(TestMethodWithMismatchedParamsTestCases.class); + + assertThat(results) + .hasSingleFailedTest() + .withExceptionInstanceOf(ParameterResolutionException.class) + .hasMessageMatching("Parameter.*is not of the correct target type.*"); } } @@ -394,11 +373,12 @@ class WhenTestClassHasTestMethodWithParameterAnnotatedWithBothNewAndSharedTests @DisplayName("then an exception is thrown") @Test void thenExceptionIsThrown() throws Exception { - ExecutionResults executionResults = PioneerTestKit - .executeTestClass(TestMethodWithParameterAnnotatedWithBothNewAndSharedTestCases.class); + ExecutionResults results = executeTestClass( + TestMethodWithParameterAnnotatedWithBothNewAndSharedTestCases.class); Method failingTest = TestMethodWithParameterAnnotatedWithBothNewAndSharedTestCases.class .getDeclaredMethod("test", String.class); - assertThat(executionResults) + + assertThat(results) .hasSingleFailedTest() .withExceptionInstanceOf(ParameterResolutionException.class) .hasMessage("Parameter [%s] in method [%s] is annotated with both @New and @Shared", @@ -436,39 +416,25 @@ class WhenParameterIsAnnotatedWithSharedAndAnotherParamIsAnnotatedWithSharedWith @DisplayName("then it throws an exception") @Test void thenItThrowsAnException() { - ExecutionResults executionResults = PioneerTestKit - .executeTestClass(SingleTestMethodWithParamsWithSharedSameNameButDifferentTypesTestCases.class); - executionResults - .allEvents() - .debug() - .assertThatEvents() - .haveExactly( // - 1, // - finished( // - throwable( // - instanceOf(ParameterResolutionException.class), // - message(String - .format( - "Two or more parameters are annotated with @Shared annotations with the " - + "name \"%s\" but with different factory classes", - "some-name"))))); - - executionResults = PioneerTestKit - .executeTestClass(TwoTestMethodsWithParamsWithSharedSameNameButDifferentTypesTestCases.class); - executionResults - .allEvents() - .debug() - .assertThatEvents() - .haveExactly( // - 1, // - finished( // - throwable( // - instanceOf(ParameterResolutionException.class), // - message(String - .format( - "Two or more parameters are annotated with @Shared annotations with the " - + "name \"%s\" but with different factory classes", - "some-name"))))); + ExecutionResults results = executeTestClass( + SingleTestMethodWithParamsWithSharedSameNameButDifferentTypesTestCases.class); + assertThat(results) + .hasSingleFailedTest() + .withExceptionInstanceOf(ParameterResolutionException.class) + .hasMessage(String + .format("Two or more parameters are annotated with @Shared annotations with the " + + "name \"%s\" but with different factory classes", + "some-name")); + + results = executeTestClass(TwoTestMethodsWithParamsWithSharedSameNameButDifferentTypesTestCases.class); + + assertThat(results) + .hasSingleFailedTest() + .withExceptionInstanceOf(ParameterResolutionException.class) + .hasMessage(String + .format("Two or more parameters are annotated with @Shared annotations with the " + + "name \"%s\" but with different factory classes", + "some-name")); } } @@ -501,7 +467,7 @@ static final class OtherResourceFactory implements ResourceFactory { @Override public Resource create(List arguments) { - return () -> null; + return () -> "other"; } } @@ -516,38 +482,28 @@ class WhenParameterIsAnnotatedWithSharedAndAnotherParamIsAnnotatedWithSharedWith @DisplayName("then it throws an exception") @Test void thenItThrowsAnException() { - ExecutionResults executionResults = PioneerTestKit - .executeTestClass(TwoTestMethodsWithParamsWithSharedSameNameButDifferentScopesTestCases.class); - executionResults - .allEvents() - .debug() - .assertThatEvents() - .haveExactly( // - 1, // - finished( // - throwable( // - instanceOf(ParameterResolutionException.class), // - message(String - .format("Two or more parameters are annotated with @Shared annotations with " - + "the name \"%s\" but with different scopes", - "some-name-1"))))); - - executionResults = PioneerTestKit - .executeTestClasses(asList(TestMethodWithParamsWithSharedSameNameButDifferentScopesTestCases1.class, + ExecutionResults results = executeTestClass( + TwoTestMethodsWithParamsWithSharedSameNameButDifferentScopesTestCases.class); + + assertThat(results) + .hasSingleFailedTest() + .withExceptionInstanceOf(ParameterResolutionException.class) + .hasMessage(String + .format("Two or more parameters are annotated with @Shared annotations with " + + "the name \"%s\" but with different scopes", + "some-name-1")); + + results = executeTestClasses(List + .of(TestMethodWithParamsWithSharedSameNameButDifferentScopesTestCases1.class, TestMethodWithParamsWithSharedSameNameButDifferentScopesTestCases2.class)); - executionResults - .allEvents() - .debug() - .assertThatEvents() - .haveExactly( // - 1, // - finished( // - throwable( // - instanceOf(ParameterResolutionException.class), // - message(String - .format("Two or more parameters are annotated with @Shared annotations with " - + "the name \"%s\" but with different scopes", - "some-name-2"))))); + + assertThat(results) + .hasSingleFailedTest() + .withExceptionInstanceOf(ParameterResolutionException.class) + .hasMessage(String + .format("Two or more parameters are annotated with @Shared annotations with " + + "the name \"%s\" but with different scopes", + "some-name-2")); } } @@ -588,6 +544,15 @@ void test( } + static class TestMethodWithMismatchedParamsTestCases { + + @Test + void test(@New(DummyResourceFactory.class) Number number) { + fail("We should not get this far."); + } + + } + // --- @DisplayName("when a test method has two parameters annotated with " @@ -598,19 +563,13 @@ class WhenTestMethodHasTwoParamsAnnotatedWithSharedAnnotationWithSameFactoryAndN @DisplayName("then it throws an exception") @Test void thenItThrowsAnException() { - ExecutionResults executionResults = PioneerTestKit - .executeTestClass(TestMethodWithTwoParamsWithSameSharedAnnotationTestCases.class); - executionResults - .allEvents() - .debug() - .assertThatEvents() - .haveExactly( // - 1, // - finished( // - throwable( // - instanceOf(ParameterResolutionException.class), // - message("A test method has 2 parameters annotated with @Shared with the same " - + "factory type and name; this is redundant, so it is not allowed")))); + ExecutionResults results = executeTestClass(TestMethodWithTwoParamsWithSameSharedAnnotationTestCases.class); + + assertThat(results) + .hasSingleFailedTest() + .withExceptionInstanceOf(ParameterResolutionException.class) + .hasMessage("A test method has 2 parameters annotated with @Shared with the same " + + "factory type and name; this is redundant, so it is not allowed"); } } @@ -634,9 +593,8 @@ class WhenSharedResourceFactoryAppliedToParameterTests { @DisplayName("then ::create is called") @Test void thenCreateIsCalled() { - ExecutionResults executionResults = PioneerTestKit - .executeTestClass(CountingResourceFactory2TestCases.class); - assertThat(executionResults.testEvents().debug().succeeded().count()).isEqualTo(1); + ExecutionResults results = executeTestClass(CountingResourceFactory2TestCases.class); + assertThat(results).hasSingleSucceededTest(); } @DisplayName("and the factory throws on ::create") @@ -646,22 +604,16 @@ class AndFactoryThrowsOnCreateTests { @DisplayName("then the thrown exception is wrapped and propagated") @Test void thenThrownExceptionIsWrappedAndPropagated() { - ExecutionResults executionResults = PioneerTestKit - .executeTestClass(ThrowOnSharedRFCreateTestCases.class); - executionResults - .allEvents() - .debug() - .assertThatEvents() - .haveExactly( // - 1, // - finished( // - throwable( // - instanceOf(ParameterResolutionException.class), // - message("Unable to create a resource from `" - + ThrowOnRFCreateResourceFactory.class.getTypeName() + "`"), // - cause( // - instanceOf(EXPECTED_THROW_ON_RF_CREATE_EXCEPTION.getClass()), // - message(EXPECTED_THROW_ON_RF_CREATE_EXCEPTION.getMessage()))))); + ExecutionResults results = executeTestClass(ThrowOnSharedRFCreateTestCases.class); + + assertThat(results) + .hasSingleFailedTest() + .withExceptionInstanceOf(ParameterResolutionException.class) + .hasMessage("Unable to create a resource from `" + + ThrowOnRFCreateResourceFactory.class.getTypeName() + "`") + .cause() + .isInstanceOf(EXPECTED_THROW_ON_RF_CREATE_EXCEPTION.getClass()) + .hasMessage(EXPECTED_THROW_ON_RF_CREATE_EXCEPTION.getMessage()); } } @@ -673,18 +625,12 @@ class AndFactoryThrowsOnCloseTests { @DisplayName("then the thrown exception is propagated") @Test void thenThrownExceptionIsPropagated() { - ExecutionResults executionResults = PioneerTestKit - .executeTestClass(ThrowOnSharedRFCloseTestCases.class); - executionResults - .allEvents() - .debug() - .assertThatEvents() - .haveExactly( // - 1, // - finished( // - throwable( // - instanceOf(EXPECTED_THROW_ON_RF_CLOSE_EXCEPTION.getClass()), // - message(EXPECTED_THROW_ON_RF_CLOSE_EXCEPTION.getMessage())))); + ExecutionResults results = executeTestClass(ThrowOnSharedRFCloseTestCases.class); + + assertThat(results) + .hasSingleFailedContainer() + .withExceptionInstanceOf(EXPECTED_THROW_ON_RF_CLOSE_EXCEPTION.getClass()) + .hasMessage(EXPECTED_THROW_ON_RF_CLOSE_EXCEPTION.getMessage()); } } @@ -696,18 +642,12 @@ class AndFactoryReturnsNullOnCreateTests { @DisplayName("then a proper exception is thrown") @Test void thenProperExceptionIsThrown() { - ExecutionResults executionResults = PioneerTestKit - .executeTestClass(SharedRFCreateReturnsNullTestCases.class); - executionResults - .allEvents() - .debug() - .assertThatEvents() - .haveExactly( // - 1, // - finished( // - throwable( // - instanceOf(ParameterResolutionException.class), // - message(message -> message.matches(".*`Resource` instance.*was null.*"))))); + ExecutionResults results = executeTestClass(SharedRFCreateReturnsNullTestCases.class); + + assertThat(results) + .hasSingleFailedTest() + .withExceptionInstanceOf(ParameterResolutionException.class) + .hasMessageMatching(".*`Resource` instance.*was null.*"); } } @@ -723,22 +663,16 @@ class AndResourceThrowsOnGetTests { @DisplayName("then the thrown exception is wrapped and propagated") @Test void thenThrownExceptionIsWrappedAndPropagated() { - ExecutionResults executionResults = PioneerTestKit - .executeTestClass(ThrowOnSharedRGetTestCases.class); - executionResults - .allEvents() - .debug() - .assertThatEvents() - .haveExactly( // - 1, // - finished( // - throwable( // - instanceOf(ParameterResolutionException.class), // - message("Unable to get the contents of the resource created by `" - + ThrowOnRGetResourceFactory.class + "`"), // - cause( // - instanceOf(EXPECTED_THROW_ON_R_GET_EXCEPTION.getClass()), // - message(EXPECTED_THROW_ON_R_GET_EXCEPTION.getMessage()))))); + ExecutionResults results = executeTestClass(ThrowOnSharedRGetTestCases.class); + + assertThat(results) + .hasSingleFailedTest() + .withExceptionInstanceOf(ParameterResolutionException.class) + .hasMessage("Unable to get the contents of the resource created by `" + + ThrowOnRGetResourceFactory.class + "`") + .cause() + .isInstanceOf(EXPECTED_THROW_ON_R_GET_EXCEPTION.getClass()) + .hasMessage(EXPECTED_THROW_ON_R_GET_EXCEPTION.getMessage()); } } @@ -750,18 +684,12 @@ class AndResourceThrowsOnCloseTests { @DisplayName("then the thrown exception is propagated") @Test void thenThrownExceptionIsWrappedAndPropagated() { - ExecutionResults executionResults = PioneerTestKit - .executeTestClass(ThrowOnSharedRCloseTestCases.class); - executionResults - .allEvents() - .debug() - .assertThatEvents() - .haveExactly( // - 1, // - finished( // - throwable( // - instanceOf(EXPECTED_THROW_ON_R_CLOSE_EXCEPTION.getClass()), // - message(EXPECTED_THROW_ON_R_CLOSE_EXCEPTION.getMessage())))); + ExecutionResults results = executeTestClass(ThrowOnSharedRCloseTestCases.class); + + assertThat(results) + .hasSingleFailedContainer() + .withExceptionInstanceOf(EXPECTED_THROW_ON_R_CLOSE_EXCEPTION.getClass()) + .hasMessage(EXPECTED_THROW_ON_R_CLOSE_EXCEPTION.getMessage()); } } @@ -773,18 +701,12 @@ class AndResourceReturnsNullOnGetTests { @DisplayName("then a proper exception is thrown") @Test void thenProperExceptionIsThrown() { - ExecutionResults executionResults = PioneerTestKit - .executeTestClass(SharedRGetReturnsNullTestCases.class); - executionResults - .allEvents() - .debug() - .assertThatEvents() - .haveExactly( // - 1, // - finished( // - throwable( // - instanceOf(ParameterResolutionException.class), // - message(message -> message.matches(".*resource.*was null.*"))))); + ExecutionResults results = executeTestClass(SharedRGetReturnsNullTestCases.class); + + assertThat(results) + .hasSingleFailedTest() + .withExceptionInstanceOf(ParameterResolutionException.class) + .hasMessageMatching(".*resource.*was null.*"); } } @@ -884,9 +806,9 @@ class WhenSharedResourceFactoryAppliedToTwoParametersTests { @DisplayName("then ::create is called only once") @Test void thenCreateIsCalledOnlyOnce() { - ExecutionResults executionResults = PioneerTestKit - .executeTestClass(CountingResourceFactory3TestCases.class); - assertThat(executionResults.testEvents().debug().succeeded().count()).isEqualTo(2); + ExecutionResults results = executeTestClass(CountingResourceFactory3TestCases.class); + + assertThat(results).hasNumberOfSucceededTests(2); assertThat(CountingResourceFactory3.createCalls).isEqualTo(1); } diff --git a/src/test/java/org/junitpioneer/jupiter/resource/TemporaryDirectoryTests.java b/src/test/java/org/junitpioneer/jupiter/resource/TemporaryDirectoryTests.java index 805d470d4..b55dc3406 100644 --- a/src/test/java/org/junitpioneer/jupiter/resource/TemporaryDirectoryTests.java +++ b/src/test/java/org/junitpioneer/jupiter/resource/TemporaryDirectoryTests.java @@ -11,7 +11,7 @@ package org.junitpioneer.jupiter.resource; import static java.util.Arrays.asList; -import static org.junit.jupiter.api.Assertions.fail; +import static org.assertj.core.api.Assertions.fail; import static org.junit.platform.testkit.engine.EventConditions.finished; import static org.junit.platform.testkit.engine.TestExecutionResultConditions.cause; import static org.junit.platform.testkit.engine.TestExecutionResultConditions.instanceOf;