diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index 01ee0ea7b..82a875e8d 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -1,4 +1,4 @@ -# Reformates code according to google-java-format rules +# Reformats code according to google-java-format rules 263194cec89d64eeedfb667bfe59c3edd03c711f # Cleans up awkwardly formatterd code d698561e58fce0a498ccc9c43539046b5f9a6ddf @@ -6,3 +6,5 @@ d698561e58fce0a498ccc9c43539046b5f9a6ddf a9aba4023da451dba32fcf7189348e3e063feaf4 # Reformats after prettier-java update a3246612e0cb7173d4edd068eaa5bb017b0468da +# Reformats according to Eclipse formatter +9d24f8eea0c4989649722d997d529bb25f7d0d4d diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 2950ee4ec..ac2d8bd62 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -13,5 +13,5 @@ Before you continue, please consider the following: # NOTE -- Please run `mvn prettier:write` to format the code before opening a PR. Otherwise, GitHub Actions will complain at you 😉. Unfortunately, you will need to have Node installed to do so. -- Mutation tests will be run by [PITest](https://pitest.org/) after opening the PR. It will post comments in the PR for each issue found. Please take a look at them, but if the comments don't make sense, please don't worry about them. +- Please run `mvn spotless:apply` to format the code before opening a PR. Otherwise, GitHub Actions will complain at you 😉. +- Mutation tests will be run by [PITest](https://pitest.org/) after opening the PR. It will post comments in the PR for each issue found. Please take a look and fix what makes sense, but don't worry about the ones that don't. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d04fe0341..2b6ba03b5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -65,9 +65,7 @@ jobs: if: ${{ !(matrix.experimental && github.event_name == 'pull_request') }} uses: actions/cache@v4 with: - path: | - ~/.m2/repository - target/spotless-node-modules-prettier-format + path: ~/.m2/repository key: ${{ runner.os }}-mvn-${{ matrix.cache-id }}-${{ hashFiles('**/pom.xml') }} restore-keys: | ${{ runner.os }}-mvn-${{ matrix.cache-id }} diff --git a/.prettierrc.yml b/.prettierrc.yml deleted file mode 100644 index 9ce888bdf..000000000 --- a/.prettierrc.yml +++ /dev/null @@ -1,4 +0,0 @@ -tabWidth: 4 -printWidth: 100 -trailingComma: "none" -endOfLine: "lf" diff --git a/README.md b/README.md index bd16f08b8..55592ef6d 100644 --- a/README.md +++ b/README.md @@ -89,7 +89,7 @@ There are several Maven profiles that can be enabled or disabled: ## Formatting -EqualsVerifier uses [Prettier-Java](https://github.com/jhipster/prettier-java) through [prettier-maven-plugin](https://github.com/HubSpot/prettier-maven-plugin) to format Java files. You can call it using `mvn clean verify`, or run `mvn prettier:write` to only run the formatter. +EqualsVerifier uses [Spotless for Maven](https://github.com/diffplug/spotless/tree/main/plugin-maven) with a custom [Eclipse configuration](https://github.com/jqno/equalsverifier/blob/main/build/eclipse-formatter-config.xml) to format Java files. You can check formatting using `mvn clean verify`, or run `mvn spotless:apply` to fix any formatting issues automatically. ## Modules diff --git a/checkstyle-config.xml b/build/checkstyle-config.xml similarity index 100% rename from checkstyle-config.xml rename to build/checkstyle-config.xml diff --git a/build/eclipse-formatter-config.importorder b/build/eclipse-formatter-config.importorder new file mode 100644 index 000000000..ccf0d32c8 --- /dev/null +++ b/build/eclipse-formatter-config.importorder @@ -0,0 +1,5 @@ +#Organize Import Order +#Mon Dec 09 20:14:26 CET 2024 +0=\# +1=java +2= diff --git a/build/eclipse-formatter-config.xml b/build/eclipse-formatter-config.xml new file mode 100644 index 000000000..89cd87b37 --- /dev/null +++ b/build/eclipse-formatter-config.xml @@ -0,0 +1,404 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/equalsverifier-11/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/JavaFxClassesTest.java b/equalsverifier-11/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/JavaFxClassesTest.java index a1bca7fae..45528b321 100644 --- a/equalsverifier-11/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/JavaFxClassesTest.java +++ b/equalsverifier-11/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/JavaFxClassesTest.java @@ -18,6 +18,7 @@ import javafx.collections.ObservableList; import javafx.collections.ObservableMap; import javafx.collections.ObservableSet; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.testhelpers.types.Point; import org.junit.jupiter.api.Test; @@ -79,20 +80,19 @@ static final class JavaFxApiClassesContainer { private final StringProperty stringProperty; public JavaFxApiClassesContainer( - ObservableList observableList, - ObservableMap observableMap, - ObservableSet observableSet, - BooleanProperty booleanProperty, - DoubleProperty doubleProperty, - FloatProperty floatProperty, - IntegerProperty integerProperty, - ListProperty listProperty, - LongProperty longProperty, - MapProperty mapProperty, - ObjectProperty objectProperty, - SetProperty setProperty, - StringProperty stringProperty - ) { + ObservableList observableList, + ObservableMap observableMap, + ObservableSet observableSet, + BooleanProperty booleanProperty, + DoubleProperty doubleProperty, + FloatProperty floatProperty, + IntegerProperty integerProperty, + ListProperty listProperty, + LongProperty longProperty, + MapProperty mapProperty, + ObjectProperty objectProperty, + SetProperty setProperty, + StringProperty stringProperty) { this.observableList = observableList; this.observableMap = observableMap; this.observableSet = observableSet; diff --git a/equalsverifier-16/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/PrefabValuesForFieldInRecordTest.java b/equalsverifier-16/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/PrefabValuesForFieldInRecordTest.java index c0f29a826..affdab7ba 100644 --- a/equalsverifier-16/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/PrefabValuesForFieldInRecordTest.java +++ b/equalsverifier-16/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/PrefabValuesForFieldInRecordTest.java @@ -9,47 +9,43 @@ public class PrefabValuesForFieldInRecordTest { @Test public void fail_whenRecordHasSinglePrecondition() { ExpectedException - .when(() -> EqualsVerifier.forClass(SinglePrecondition.class).verify()) - .assertFailure() - .assertMessageContains("Record:", "failed to run constructor", "[1]"); + .when(() -> EqualsVerifier.forClass(SinglePrecondition.class).verify()) + .assertFailure() + .assertMessageContains("Record:", "failed to run constructor", "[1]"); } @Test public void succeed_whenRecordHasSinglePrecondition_givenPrefabValuesForField() { - EqualsVerifier - .forClass(SinglePrecondition.class) - .withPrefabValuesForField("i", 111, 142) - .verify(); + EqualsVerifier.forClass(SinglePrecondition.class).withPrefabValuesForField("i", 111, 142).verify(); } @Test public void fail_whenRecordHasDualPrecondition() { ExpectedException - .when(() -> EqualsVerifier.forClass(DualPrecondition.class).verify()) - .assertFailure() - .assertMessageContains("Record:", "failed to run constructor", "[1, 1]"); + .when(() -> EqualsVerifier.forClass(DualPrecondition.class).verify()) + .assertFailure() + .assertMessageContains("Record:", "failed to run constructor", "[1, 1]"); } @Test public void fail_whenRecordHasDualPrecondition_givenPrefabValuesForOnlyOneField() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(DualPrecondition.class) - .withPrefabValuesForField("x", 111, 142) - .verify() - ) - .assertFailure() - .assertMessageContains("Record:", "failed to run constructor", "[111, 1]"); + .when( + () -> EqualsVerifier + .forClass(DualPrecondition.class) + .withPrefabValuesForField("x", 111, 142) + .verify()) + .assertFailure() + .assertMessageContains("Record:", "failed to run constructor", "[111, 1]"); } @Test public void succeed_whenRecordHasDualPrecondition_givenPrefabValueForBothFields() { EqualsVerifier - .forClass(DualPrecondition.class) - .withPrefabValuesForField("x", 111, 142) - .withPrefabValuesForField("y", 505, 555) - .verify(); + .forClass(DualPrecondition.class) + .withPrefabValuesForField("x", 111, 142) + .withPrefabValuesForField("y", 505, 555) + .verify(); } record SinglePrecondition(int i) { diff --git a/equalsverifier-16/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/RecordsTest.java b/equalsverifier-16/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/RecordsTest.java index fd6aa50ae..222535559 100644 --- a/equalsverifier-16/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/RecordsTest.java +++ b/equalsverifier-16/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/RecordsTest.java @@ -6,6 +6,7 @@ import java.io.Serializable; import java.util.Objects; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.reflection.RecordsHelper; @@ -33,9 +34,9 @@ public void succeed_whenClassIsAPrivateRecord() { @Test public void fail_whenConstructorChecksNull() { ExpectedException - .when(() -> EqualsVerifier.forClass(NullCheckingRecord.class).verify()) - .assertFailure() - .assertMessageContains("Record:", "failed to run constructor", "Warning.NULL_FIELDS"); + .when(() -> EqualsVerifier.forClass(NullCheckingRecord.class).verify()) + .assertFailure() + .assertMessageContains("Record:", "failed to run constructor", "Warning.NULL_FIELDS"); } @Test @@ -46,33 +47,33 @@ public void succeed_whenConstructorChecksNull_givenSuppressedWarning() { @Test public void fail_whenConstructorChecksValue() { ExpectedException - .when(() -> EqualsVerifier.forClass(ValueCheckingRecord.class).verify()) - .assertFailure() - .assertMessageContains("Record:", "failed to run constructor", "prefab values"); + .when(() -> EqualsVerifier.forClass(ValueCheckingRecord.class).verify()) + .assertFailure() + .assertMessageContains("Record:", "failed to run constructor", "prefab values"); } @Test public void fail_whenRecordInvariantIsViolated_givenIntFieldIsModifiedInConstructor() { ExpectedException - .when(() -> EqualsVerifier.forClass(BrokenInvariantIntFieldRecord.class).verify()) - .assertFailure() - .assertMessageContains("Record invariant", "intField"); + .when(() -> EqualsVerifier.forClass(BrokenInvariantIntFieldRecord.class).verify()) + .assertFailure() + .assertMessageContains("Record invariant", "intField"); } @Test public void fail_whenRecordInvariantIsViolated_givenStringFieldIsModifiedInConstructor() { ExpectedException - .when(() -> EqualsVerifier.forClass(BrokenInvariantStringFieldRecord.class).verify()) - .assertFailure() - .assertMessageContains("Record invariant", "stringField"); + .when(() -> EqualsVerifier.forClass(BrokenInvariantStringFieldRecord.class).verify()) + .assertFailure() + .assertMessageContains("Record invariant", "stringField"); } @Test public void fail_whenRecordInvariantIsViolated_givenBothFieldsAreModifiedInConstructor() { ExpectedException - .when(() -> EqualsVerifier.forClass(BrokenInvariantBothRecord.class).verify()) - .assertFailure() - .assertMessageContains("Record invariant", "intField", "stringField"); + .when(() -> EqualsVerifier.forClass(BrokenInvariantBothRecord.class).verify()) + .assertFailure() + .assertMessageContains("Record invariant", "intField", "stringField"); } @Test @@ -83,41 +84,41 @@ public void succeed_whenRecordImplementsItsOwnEquals() { @Test public void fail_whenRecordImplementsItsOwnEquals_givenNotAllFieldsAreUsed() { ExpectedException - .when(() -> EqualsVerifier.forClass(NotAllFieldsRecord.class).verify()) - .assertFailure() - .assertMessageContains("Significant fields"); + .when(() -> EqualsVerifier.forClass(NotAllFieldsRecord.class).verify()) + .assertFailure() + .assertMessageContains("Significant fields"); } @Test public void fail_whenRecordConstructorThrows() { ExpectedException - .when(() -> EqualsVerifier.forClass(ThrowingConstructorRecord.class).verify()) - .assertFailure() - .assertMessageContains("Record", "failed to run constructor"); + .when(() -> EqualsVerifier.forClass(ThrowingConstructorRecord.class).verify()) + .assertFailure() + .assertMessageContains("Record", "failed to run constructor"); } @Test public void fail_whenRecordConstructorThrowsNpe() { ExpectedException - .when(() -> EqualsVerifier.forClass(NullFieldRecord.class).verify()) - .assertFailure() - .assertMessageContains("Record", "failed to run constructor"); + .when(() -> EqualsVerifier.forClass(NullFieldRecord.class).verify()) + .assertFailure() + .assertMessageContains("Record", "failed to run constructor"); } @Test public void fail_whenRecordAccessorThrows() { ExpectedException - .when(() -> EqualsVerifier.forClass(ThrowingAccessorRecord.class).verify()) - .assertFailure() - .assertMessageContains("Record", "failed to run accessor method"); + .when(() -> EqualsVerifier.forClass(ThrowingAccessorRecord.class).verify()) + .assertFailure() + .assertMessageContains("Record", "failed to run accessor method"); } @Test public void fail_whenRecordAccessorThrowsNpe() { ExpectedException - .when(() -> EqualsVerifier.forClass(NullAccessorRecord.class).verify()) - .assertFailure() - .assertMessageContains("Record", "failed to run accessor method", "s()"); + .when(() -> EqualsVerifier.forClass(NullAccessorRecord.class).verify()) + .assertFailure() + .assertMessageContains("Record", "failed to run accessor method", "s()"); } @Test @@ -128,9 +129,9 @@ public void succeed_whenRecordContainsStaticField() { @Test public void succeed_whenRecordValidatesInput_givenValidPrefabValues() { EqualsVerifier - .forClass(ValidatingConstructorRecord.class) - .withPrefabValues(String.class, "valid-1", "valid-2") - .verify(); + .forClass(ValidatingConstructorRecord.class) + .withPrefabValues(String.class, "valid-1", "valid-2") + .verify(); } @Test diff --git a/equalsverifier-16/src/test/java/nl/jqno/equalsverifier/internal/instantiation/RecordInstanceCreatorTest.java b/equalsverifier-16/src/test/java/nl/jqno/equalsverifier/internal/instantiation/RecordInstanceCreatorTest.java index 69a0ea94a..891160c18 100644 --- a/equalsverifier-16/src/test/java/nl/jqno/equalsverifier/internal/instantiation/RecordInstanceCreatorTest.java +++ b/equalsverifier-16/src/test/java/nl/jqno/equalsverifier/internal/instantiation/RecordInstanceCreatorTest.java @@ -5,6 +5,7 @@ import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; + import nl.jqno.equalsverifier.internal.reflection.ClassProbe; import org.junit.jupiter.api.Test; import org.objenesis.ObjenesisStd; diff --git a/equalsverifier-16/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/RecordFallbackFactoryTest.java b/equalsverifier-16/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/RecordFallbackFactoryTest.java index 4b003c695..03190df2e 100644 --- a/equalsverifier-16/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/RecordFallbackFactoryTest.java +++ b/equalsverifier-16/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/RecordFallbackFactoryTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertNotSame; import java.util.LinkedHashSet; + import nl.jqno.equalsverifier.internal.instantiation.vintage.FactoryCache; import nl.jqno.equalsverifier.internal.instantiation.vintage.VintageValueProvider; import nl.jqno.equalsverifier.internal.reflection.Tuple; @@ -32,11 +33,7 @@ public void setUp() { @Test public void redCopyHasTheSameValuesAsRed_whenSutContainsGenericValueThatNeedsToBeIdenticalInRedAndRedCopy() { - Tuple tuple = factory.createValues( - new TypeTag(GenericRecordContainer.class), - valueProvider, - typeStack - ); + Tuple tuple = factory.createValues(new TypeTag(GenericRecordContainer.class), valueProvider, typeStack); assertEquals(tuple.getRed(), tuple.getRedCopy()); assertNotSame(tuple.getRed(), tuple.getRedCopy()); diff --git a/equalsverifier-16/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/RecordObjectAccessorCopyingTest.java b/equalsverifier-16/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/RecordObjectAccessorCopyingTest.java index 09720656a..c90cc8044 100644 --- a/equalsverifier-16/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/RecordObjectAccessorCopyingTest.java +++ b/equalsverifier-16/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/RecordObjectAccessorCopyingTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertSame; import java.lang.reflect.Field; + import nl.jqno.equalsverifier.internal.reflection.FieldIterable; import nl.jqno.equalsverifier.internal.reflection.Instantiator; import org.junit.jupiter.api.Test; diff --git a/equalsverifier-16/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/RecordObjectAccessorScramblingTest.java b/equalsverifier-16/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/RecordObjectAccessorScramblingTest.java index 171b5dcc9..b85de0f78 100644 --- a/equalsverifier-16/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/RecordObjectAccessorScramblingTest.java +++ b/equalsverifier-16/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/RecordObjectAccessorScramblingTest.java @@ -6,6 +6,7 @@ import java.lang.reflect.Constructor; import java.util.LinkedHashSet; + import nl.jqno.equalsverifier.internal.instantiation.JavaApiPrefabValues; import nl.jqno.equalsverifier.internal.instantiation.vintage.FactoryCache; import nl.jqno.equalsverifier.internal.instantiation.vintage.VintageValueProvider; @@ -37,14 +38,13 @@ public void scrambleLeavesOriginalUnaffected() throws Exception { @Test public void scramble() throws Exception { Constructor constructor = Point.class.getDeclaredConstructor(int.class, int.class); - factoryCache.put( - Point.class, - values( - constructor.newInstance(1, 2), - constructor.newInstance(2, 3), - constructor.newInstance(1, 2) - ) - ); + factoryCache + .put( + Point.class, + values( + constructor.newInstance(1, 2), + constructor.newInstance(2, 3), + constructor.newInstance(1, 2))); Object original = constructor.newInstance(1, 2); Object scrambled = doScramble(original); diff --git a/equalsverifier-16/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/RecordObjectAccessorTest.java b/equalsverifier-16/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/RecordObjectAccessorTest.java index 6934991b4..5380532f0 100644 --- a/equalsverifier-16/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/RecordObjectAccessorTest.java +++ b/equalsverifier-16/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/RecordObjectAccessorTest.java @@ -6,6 +6,7 @@ import java.lang.reflect.Constructor; import java.util.LinkedHashSet; import java.util.Objects; + import nl.jqno.equalsverifier.internal.exceptions.ReflectionException; import nl.jqno.equalsverifier.internal.instantiation.JavaApiPrefabValues; import nl.jqno.equalsverifier.internal.instantiation.vintage.VintageValueProvider; @@ -25,8 +26,7 @@ public class RecordObjectAccessorTest { @BeforeEach public void setUp() throws Exception { - Constructor constructor = - SimpleRecord.class.getDeclaredConstructor(int.class, String.class); + Constructor constructor = SimpleRecord.class.getDeclaredConstructor(int.class, String.class); constructor.setAccessible(true); objenesis = new ObjenesisStd(); recordInstance = constructor.newInstance(42, "hello"); @@ -46,39 +46,33 @@ public void get() { @Test public void fail_whenConstructorThrowsNpe() { - Object instance = Instantiator - .of(NpeThrowingConstructorRecord.class, objenesis) - .instantiate(); + Object instance = Instantiator.of(NpeThrowingConstructorRecord.class, objenesis).instantiate(); ExpectedException - .when(() -> accessorFor(instance).copy(objenesis)) - .assertThrows(ReflectionException.class) - .assertMessageContains("Record:", "failed to run constructor", "Warning.NULL_FIELDS"); + .when(() -> accessorFor(instance).copy(objenesis)) + .assertThrows(ReflectionException.class) + .assertMessageContains("Record:", "failed to run constructor", "Warning.NULL_FIELDS"); } @Test public void fail_whenConstructorThrowsOnZero() { - Object instance = Instantiator - .of(ZeroThrowingConstructorRecord.class, objenesis) - .instantiate(); + Object instance = Instantiator.of(ZeroThrowingConstructorRecord.class, objenesis).instantiate(); ExpectedException - .when(() -> accessorFor(instance).copy(objenesis)) - .assertThrows(ReflectionException.class) - .assertMessageContains("Record:", "failed to run constructor", "Warning.ZERO_FIELDS"); + .when(() -> accessorFor(instance).copy(objenesis)) + .assertThrows(ReflectionException.class) + .assertMessageContains("Record:", "failed to run constructor", "Warning.ZERO_FIELDS"); } @Test public void fail_whenConstructorThrowsOnSomethingElse() { - Object instance = Instantiator - .of(OtherThrowingConstructorRecord.class, objenesis) - .instantiate(); + Object instance = Instantiator.of(OtherThrowingConstructorRecord.class, objenesis).instantiate(); VintageValueProvider vp = new VintageValueProvider(JavaApiPrefabValues.build(), objenesis); ExpectedException - .when(() -> accessorFor(instance).scramble(vp, TypeTag.NULL, EMPTY_TYPE_STACK)) - .assertThrows(ReflectionException.class) - .assertMessageContains("Record:", "failed to run constructor", "prefab values"); + .when(() -> accessorFor(instance).scramble(vp, TypeTag.NULL, EMPTY_TYPE_STACK)) + .assertThrows(ReflectionException.class) + .assertMessageContains("Record:", "failed to run constructor", "prefab values"); } @SuppressWarnings("unchecked") diff --git a/equalsverifier-17/src/main/java/nl/jqno/equalsverifier/internal/reflection/SealedTypesHelper.java b/equalsverifier-17/src/main/java/nl/jqno/equalsverifier/internal/reflection/SealedTypesHelper.java index be5774cd9..52bcbd519 100644 --- a/equalsverifier-17/src/main/java/nl/jqno/equalsverifier/internal/reflection/SealedTypesHelper.java +++ b/equalsverifier-17/src/main/java/nl/jqno/equalsverifier/internal/reflection/SealedTypesHelper.java @@ -2,6 +2,7 @@ import java.lang.reflect.Modifier; import java.util.Optional; + import nl.jqno.equalsverifier.internal.exceptions.EqualsVerifierInternalBugException; public final class SealedTypesHelper { @@ -17,9 +18,8 @@ public static Optional> findInstantiableSubclass(Class } private static Optional> findInstantiablePermittedClass( - Class type, - boolean checkCurrent - ) { + Class type, + boolean checkCurrent) { if (checkCurrent && (!isAbstract(type) || !type.isSealed())) { @SuppressWarnings("unchecked") var result = (Class) type; @@ -39,8 +39,7 @@ private static Optional> findInstantiablePermittedClas } } throw new EqualsVerifierInternalBugException( - "Could not find a non-sealed subtype for " + type.getCanonicalName() - ); + "Could not find a non-sealed subtype for " + type.getCanonicalName()); } private static boolean isAbstract(Class type) { diff --git a/equalsverifier-17/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/SealedTypesRecursionTest.java b/equalsverifier-17/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/SealedTypesRecursionTest.java index e1adf31da..1241ff2e0 100644 --- a/equalsverifier-17/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/SealedTypesRecursionTest.java +++ b/equalsverifier-17/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/SealedTypesRecursionTest.java @@ -1,6 +1,7 @@ package nl.jqno.equalsverifier.integration.extended_contract; import java.util.Objects; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; import org.junit.jupiter.api.Test; @@ -12,14 +13,13 @@ public void dontThrowStackOverflowError_whenOnlyPermittedSubclassInSealedInterfa // A container with a field of a sealed interface. // The sealed interface permits only 1 type, which refers back to the container. ExpectedException - .when(() -> EqualsVerifier.forClass(SealedContainer.class).verify()) - .assertFailure() - .assertMessageContains( - "Recursive datastructure", - "Add prefab values for one of the following types", - "SealedContainer", - "SealedInterface" - ); + .when(() -> EqualsVerifier.forClass(SealedContainer.class).verify()) + .assertFailure() + .assertMessageContains( + "Recursive datastructure", + "Add prefab values for one of the following types", + "SealedContainer", + "SealedInterface"); } @Test @@ -27,14 +27,13 @@ public void dontThrowStackOverflowError_whenOnlyPermittedRecordInSealedInterface // A container with a field of a sealed interface. // The sealed interface permits only 1 type, which is a record that refers back to the container. ExpectedException - .when(() -> EqualsVerifier.forClass(SealedRecordContainer.class).verify()) - .assertFailure() - .assertMessageContains( - "Recursive datastructure", - "Add prefab values for one of the following types", - "SealedRecordContainer", - "SealedRecordInterface" - ); + .when(() -> EqualsVerifier.forClass(SealedRecordContainer.class).verify()) + .assertFailure() + .assertMessageContains( + "Recursive datastructure", + "Add prefab values for one of the following types", + "SealedRecordContainer", + "SealedRecordInterface"); } static final class SealedContainer { @@ -120,5 +119,5 @@ public boolean equals(Object obj) { sealed interface SealedRecordInterface permits OnlyPermittedRecordImplementation {} static final record OnlyPermittedRecordImplementation(SealedRecordContainer container) - implements SealedRecordInterface {} + implements SealedRecordInterface {} } diff --git a/equalsverifier-17/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/SealedTypesTest.java b/equalsverifier-17/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/SealedTypesTest.java index dfe514072..3c10b7843 100644 --- a/equalsverifier-17/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/SealedTypesTest.java +++ b/equalsverifier-17/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/SealedTypesTest.java @@ -1,6 +1,7 @@ package nl.jqno.equalsverifier.integration.extended_contract; import java.util.Objects; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; import org.junit.jupiter.api.Test; @@ -10,16 +11,16 @@ public class SealedTypesTest { @Test public void succeed_whenSealedParentHasAFinalChild_givenItHasCorrectEqualsAndHashCode() { EqualsVerifier - .forClass(SealedParentWithFinalChild.class) - .withRedefinedSubclass(FinalSealedChild.class) - .verify(); + .forClass(SealedParentWithFinalChild.class) + .withRedefinedSubclass(FinalSealedChild.class) + .verify(); } @Test public void fail_whenSealedParentHasAFinalChild_givenEqualsVerifierIsCalledIncorrectly() { ExpectedException - .when(() -> EqualsVerifier.forClass(SealedParentWithFinalChild.class).verify()) - .assertFailure(); + .when(() -> EqualsVerifier.forClass(SealedParentWithFinalChild.class).verify()) + .assertFailure(); } @Test @@ -30,16 +31,16 @@ public void succeed_whenFinalChildHasCorrectEqualsAndHashCode() { @Test public void succeed_whenSealedParentHasANonsealedChild_givenItHasCorrectEqualsAndHashCode() { EqualsVerifier - .forClass(SealedParentWithNonsealedChild.class) - .withRedefinedSubclass(NonsealedSealedChild.class) - .verify(); + .forClass(SealedParentWithNonsealedChild.class) + .withRedefinedSubclass(NonsealedSealedChild.class) + .verify(); } @Test public void fail_whenSealedParentHasANonsealedChild_givenEqualsVerifierIsCalledIncorrectly() { ExpectedException - .when(() -> EqualsVerifier.forClass(SealedParentWithNonsealedChild.class).verify()) - .assertFailure(); + .when(() -> EqualsVerifier.forClass(SealedParentWithNonsealedChild.class).verify()) + .assertFailure(); } @Test @@ -55,13 +56,12 @@ public void succeed_whenClassContainsASealedType() { @Test public void fail_whenSealeadParentHasAnIncorrectImplementationOfEquals() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(IncorrectSealedParent.class) - .withRedefinedSubclass(IncorrectSealedChild.class) - .verify() - ) - .assertFailure(); + .when( + () -> EqualsVerifier + .forClass(IncorrectSealedParent.class) + .withRedefinedSubclass(IncorrectSealedChild.class) + .verify()) + .assertFailure(); } @Test @@ -113,8 +113,7 @@ public int hashCode() { } } - public abstract static sealed class SealedParentWithNonsealedChild - permits NonsealedSealedChild { + public abstract static sealed class SealedParentWithNonsealedChild permits NonsealedSealedChild { private final int i; @@ -159,20 +158,17 @@ public final class SealedTypeContainer { private final SealedParentWithNonsealedChild sealedWithNonsealedChild; public SealedTypeContainer( - SealedParentWithFinalChild sealedWithFinalChild, - SealedParentWithNonsealedChild sealedWithNonsealedChild - ) { + SealedParentWithFinalChild sealedWithFinalChild, + SealedParentWithNonsealedChild sealedWithNonsealedChild) { this.sealedWithFinalChild = sealedWithFinalChild; this.sealedWithNonsealedChild = sealedWithNonsealedChild; } @Override public boolean equals(Object obj) { - return ( - obj instanceof SealedTypeContainer other && - Objects.equals(sealedWithFinalChild, other.sealedWithFinalChild) && - Objects.equals(sealedWithNonsealedChild, other.sealedWithNonsealedChild) - ); + return obj instanceof SealedTypeContainer other + && Objects.equals(sealedWithFinalChild, other.sealedWithFinalChild) + && Objects.equals(sealedWithNonsealedChild, other.sealedWithNonsealedChild); } @Override @@ -217,11 +213,9 @@ protected SealedParentWithTwoChildren(String value) { @Override public boolean equals(Object other) { - return ( - other != null && - (this.getClass() == other.getClass()) && - Objects.equals(this.value, ((SealedParentWithTwoChildren) other).value) - ); + return other != null + && (this.getClass() == other.getClass()) + && Objects.equals(this.value, ((SealedParentWithTwoChildren) other).value); } @Override diff --git a/equalsverifier-17/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/SealedTypesFallbackFactoryTest.java b/equalsverifier-17/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/SealedTypesFallbackFactoryTest.java index 88b60c153..554090488 100644 --- a/equalsverifier-17/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/SealedTypesFallbackFactoryTest.java +++ b/equalsverifier-17/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/SealedTypesFallbackFactoryTest.java @@ -6,6 +6,7 @@ import java.util.LinkedHashSet; import java.util.Objects; + import nl.jqno.equalsverifier.internal.instantiation.vintage.FactoryCache; import nl.jqno.equalsverifier.internal.instantiation.vintage.VintageValueProvider; import nl.jqno.equalsverifier.internal.reflection.Tuple; @@ -33,11 +34,7 @@ public void setUp() { @Test public void redCopyHasTheSameValuesAsRed_whenSutIsAbstractSealedAndPermittedTypeAddsField() { - Tuple tuple = factory.createValues( - new TypeTag(SealedParentWithFinalChild.class), - valueProvider, - typeStack - ); + Tuple tuple = factory.createValues(new TypeTag(SealedParentWithFinalChild.class), valueProvider, typeStack); assertEquals(tuple.getRed(), tuple.getRedCopy()); assertNotSame(tuple.getRed(), tuple.getRedCopy()); diff --git a/equalsverifier-17/src/test/java/nl/jqno/equalsverifier/internal/reflection/SealedTypesHelperTest.java b/equalsverifier-17/src/test/java/nl/jqno/equalsverifier/internal/reflection/SealedTypesHelperTest.java index 2b5f64c23..643dc4d26 100644 --- a/equalsverifier-17/src/test/java/nl/jqno/equalsverifier/internal/reflection/SealedTypesHelperTest.java +++ b/equalsverifier-17/src/test/java/nl/jqno/equalsverifier/internal/reflection/SealedTypesHelperTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Optional; + import org.junit.jupiter.api.Test; public class SealedTypesHelperTest { diff --git a/equalsverifier-21/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/RecordPatternMatchTest.java b/equalsverifier-21/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/RecordPatternMatchTest.java index 28530c94f..b278bdaf4 100644 --- a/equalsverifier-21/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/RecordPatternMatchTest.java +++ b/equalsverifier-21/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/RecordPatternMatchTest.java @@ -14,10 +14,7 @@ void succeed_whenEqualsUsesInstanceofPatternMatch() { record Point(int x, int y) { @Override public boolean equals(Object obj) { - return ( - this == obj || - (obj instanceof Point(int otherX, int otherY) && x == otherX && y == otherY) - ); + return(this==obj||(obj instanceof Point(int otherX,int otherY)&&x==otherX&&y==otherY)); } @Override diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/ConfiguredEqualsVerifier.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/ConfiguredEqualsVerifier.java index 6d3ee7001..49c4191fc 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/ConfiguredEqualsVerifier.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/ConfiguredEqualsVerifier.java @@ -4,6 +4,7 @@ import java.util.EnumSet; import java.util.List; import java.util.function.Function; + import nl.jqno.equalsverifier.Func.Func1; import nl.jqno.equalsverifier.Func.Func2; import nl.jqno.equalsverifier.api.EqualsVerifierApi; @@ -32,11 +33,10 @@ public ConfiguredEqualsVerifier() { /** Private constructor. For internal use only. */ private ConfiguredEqualsVerifier( - EnumSet warningsToSuppress, - FactoryCache factoryCache, - boolean usingGetClass, - Function fieldnameToGetter - ) { + EnumSet warningsToSuppress, + FactoryCache factoryCache, + boolean usingGetClass, + Function fieldnameToGetter) { this.warningsToSuppress = warningsToSuppress; this.factoryCache = factoryCache; this.usingGetClass = usingGetClass; @@ -49,12 +49,10 @@ private ConfiguredEqualsVerifier( * @return a copy of the configuration. */ public ConfiguredEqualsVerifier copy() { - return new ConfiguredEqualsVerifier( - EnumSet.copyOf(warningsToSuppress), - factoryCache.copy(), - usingGetClass, - fieldnameToGetter - ); + return new ConfiguredEqualsVerifier(EnumSet.copyOf(warningsToSuppress), + factoryCache.copy(), + usingGetClass, + fieldnameToGetter); } /** {@inheritDoc} */ @@ -73,20 +71,14 @@ public ConfiguredEqualsVerifier withPrefabValues(Class otherType, S red, /** {@inheritDoc} */ @Override - public ConfiguredEqualsVerifier withGenericPrefabValues( - Class otherType, - Func1 factory - ) { + public ConfiguredEqualsVerifier withGenericPrefabValues(Class otherType, Func1 factory) { PrefabValuesApi.addGenericPrefabValues(factoryCache, otherType, factory); return this; } /** {@inheritDoc} */ @Override - public ConfiguredEqualsVerifier withGenericPrefabValues( - Class otherType, - Func2 factory - ) { + public ConfiguredEqualsVerifier withGenericPrefabValues(Class otherType, Func2 factory) { PrefabValuesApi.addGenericPrefabValues(factoryCache, otherType, factory); return this; } @@ -99,15 +91,14 @@ public ConfiguredEqualsVerifier usingGetClass() { } @Override - public ConfiguredEqualsVerifier withFieldnameToGetterConverter( - Function converter - ) { + public ConfiguredEqualsVerifier withFieldnameToGetterConverter(Function converter) { this.fieldnameToGetter = converter; return this; } /** * {@inheritDoc} + * * @deprecated No longer needed; this happens automatically. */ @Deprecated @@ -119,26 +110,23 @@ public ConfiguredEqualsVerifier withResetCaches() { /** * Factory method. For general use. * - * @param The type. + * @param The type. * @param type The class for which the {@code equals} method should be tested. * @return A fluent API for EqualsVerifier. */ public SingleTypeEqualsVerifierApi forClass(Class type) { - return new SingleTypeEqualsVerifierApi<>( - type, - EnumSet.copyOf(warningsToSuppress), - factoryCache.copy(), - objenesis, - usingGetClass, - fieldnameToGetter - ); + return new SingleTypeEqualsVerifierApi<>(type, + EnumSet.copyOf(warningsToSuppress), + factoryCache.copy(), + objenesis, + usingGetClass, + fieldnameToGetter); } /** * Factory method. For general use. * - * @param classes An iterable containing the classes for which {@code equals} method should be - * tested. + * @param classes An iterable containing the classes for which {@code equals} method should be tested. * @return A fluent API for EqualsVerifier. */ public MultipleTypeEqualsVerifierApi forClasses(Iterable> classes) { @@ -148,27 +136,21 @@ public MultipleTypeEqualsVerifierApi forClasses(Iterable> classes) { /** * Factory method. For general use. * - * @param first A class for which the {@code equals} method should be tested. + * @param first A class for which the {@code equals} method should be tested. * @param second Another class for which the {@code equals} method should be tested. - * @param more More classes for which the {@code equals} method should be tested. + * @param more More classes for which the {@code equals} method should be tested. * @return A fluent API for EqualsVerifier. */ - public MultipleTypeEqualsVerifierApi forClasses( - Class first, - Class second, - Class... more - ) { - return new MultipleTypeEqualsVerifierApi( - ListBuilders.buildListOfAtLeastTwo(first, second, more), - this - ); + public MultipleTypeEqualsVerifierApi forClasses(Class first, Class second, Class... more) { + return new MultipleTypeEqualsVerifierApi(ListBuilders.buildListOfAtLeastTwo(first, second, more), this); } /** * Factory method. For general use. * - *

Note that this operation may be slow. If the test is too slow, use {@link - * #forClasses(Class, Class, Class...)} instead. + *

+ * Note that this operation may be slow. If the test is too slow, use {@link #forClasses(Class, Class, Class...)} + * instead. * * @param packageName A package for which each class's {@code equals} should be tested. * @return A fluent API for EqualsVerifier. @@ -180,10 +162,11 @@ public MultipleTypeEqualsVerifierApi forPackage(String packageName) { /** * Factory method. For general use. * - *

Note that this operation may be slow. If the test is too slow, use {@link - * #forClasses(Class, Class, Class...)} instead. + *

+ * Note that this operation may be slow. If the test is too slow, use {@link #forClasses(Class, Class, Class...)} + * instead. * - * @param packageName A package for which each class's {@code equals} should be tested. + * @param packageName A package for which each class's {@code equals} should be tested. * @param scanRecursively true to scan all sub-packages * @return A fluent API for EqualsVerifier. */ @@ -196,14 +179,15 @@ public MultipleTypeEqualsVerifierApi forPackage(String packageName, boolean scan /** * Factory method. For general use. * - *

Note that this operation may be slow. If the test is too slow, use {@link - * #forClasses(Class, Class, Class...)} instead. + *

+ * Note that this operation may be slow. If the test is too slow, use {@link #forClasses(Class, Class, Class...)} + * instead. * - *

Also note that if {@code mustExtend} is given, and it exists within {@code packageName}, - * it will NOT be included. + *

+ * Also note that if {@code mustExtend} is given, and it exists within {@code packageName}, it will NOT be included. * * @param packageName A package for which each class's {@code equals} should be tested. - * @param mustExtend if not null, returns only classes that extend or implement this class. + * @param mustExtend if not null, returns only classes that extend or implement this class. * @return A fluent API for EqualsVerifier. */ public MultipleTypeEqualsVerifierApi forPackage(String packageName, Class mustExtend) { diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/EqualsVerifier.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/EqualsVerifier.java index 0ce4390d4..1c3cd2dd3 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/EqualsVerifier.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/EqualsVerifier.java @@ -1,6 +1,7 @@ package nl.jqno.equalsverifier; import java.util.List; + import nl.jqno.equalsverifier.api.EqualsVerifierApi; import nl.jqno.equalsverifier.api.MultipleTypeEqualsVerifierApi; import nl.jqno.equalsverifier.api.RelaxedEqualsVerifierApi; @@ -13,34 +14,39 @@ * {@code EqualsVerifier} can be used in unit tests to verify whether the contract for the {@code * equals} and {@code hashCode} methods in a class is met. * - *

The contracts are described in the Javadoc comments for {@link - * java.lang.Object#equals(Object)} and {@link java.lang.Object#hashCode()} + *

+ * The contracts are described in the Javadoc comments for {@link java.lang.Object#equals(Object)} and + * {@link java.lang.Object#hashCode()} * - *

To get started, use {@code EqualsVerifier} as follows: + *

+ * To get started, use {@code EqualsVerifier} as follows: * - *

{@code EqualsVerifier.forClass(My.class).verify();} + *

+ * {@code EqualsVerifier.forClass(My.class).verify();} * - *

Or, if that's too strict: + *

+ * Or, if that's too strict: * - *

{@code EqualsVerifier.simple().forClass(My.class).verify();} + *

+ * {@code EqualsVerifier.simple().forClass(My.class).verify();} * - *

For more information, see the documentation at http://www.jqno.nl/equalsverifier + *

+ * For more information, see the documentation at http://www.jqno.nl/equalsverifier */ public final class EqualsVerifier { /** - * Private constructor. Call {@link #forClass(Class)} or {@link #forRelaxedEqualExamples(Object, - * Object, Object...)} instead. + * Private constructor. Call {@link #forClass(Class)} or {@link #forRelaxedEqualExamples(Object, Object, Object...)} + * instead. */ private EqualsVerifier() {} /** - * Creates a configuration object that can be reused with EqualsVerifier for multiple classes. - * It has a fluent API. + * Creates a configuration object that can be reused with EqualsVerifier for multiple classes. It has a fluent API. * - *

Save the configuration in a variable of type {@link EqualsVerifierApi} and call {@link - * #forClass(Class)} on it for each class whose {@code equals} and {@code hashCode} must be - * verified. + *

+ * Save the configuration in a variable of type {@link EqualsVerifierApi} and call {@link #forClass(Class)} on it + * for each class whose {@code equals} and {@code hashCode} must be verified. * * @return A reusable configuration object with a fluent API. */ @@ -49,21 +55,20 @@ public static ConfiguredEqualsVerifier configure() { } /** - * Creates a configuration object that is pre-configured so that it can be used with most - * IDE-generated {@code equals} and {@code hashCode} methods without any further configuration. + * Creates a configuration object that is pre-configured so that it can be used with most IDE-generated + * {@code equals} and {@code hashCode} methods without any further configuration. * * @return A reusable configuration object with a fluent API. */ public static ConfiguredEqualsVerifier simple() { - return new ConfiguredEqualsVerifier() - .suppress(Warning.STRICT_INHERITANCE, Warning.NONFINAL_FIELDS); + return new ConfiguredEqualsVerifier().suppress(Warning.STRICT_INHERITANCE, Warning.NONFINAL_FIELDS); } /** * Factory method. For general use. * * @param type The class for which the {@code equals} method should be tested. - * @param The type. + * @param The type. * @return A fluent API for EqualsVerifier. */ public static SingleTypeEqualsVerifierApi forClass(Class type) { @@ -73,41 +78,32 @@ public static SingleTypeEqualsVerifierApi forClass(Class type) { /** * Factory method. For general use. * - * @param classes An iterable containing the classes for which {@code equals} method should be - * tested. + * @param classes An iterable containing the classes for which {@code equals} method should be tested. * @return A fluent API for EqualsVerifier. */ public static MultipleTypeEqualsVerifierApi forClasses(Iterable> classes) { - return new MultipleTypeEqualsVerifierApi( - ListBuilders.fromIterable(classes), - new ConfiguredEqualsVerifier() - ); + return new MultipleTypeEqualsVerifierApi(ListBuilders.fromIterable(classes), new ConfiguredEqualsVerifier()); } /** * Factory method. For general use. * - * @param first A class for which the {@code equals} method should be tested. + * @param first A class for which the {@code equals} method should be tested. * @param second Another class for which the {@code equals} method should be tested. - * @param more More classes for which the {@code equals} method should be tested. + * @param more More classes for which the {@code equals} method should be tested. * @return A fluent API for EqualsVerifier. */ - public static MultipleTypeEqualsVerifierApi forClasses( - Class first, - Class second, - Class... more - ) { - return new MultipleTypeEqualsVerifierApi( - ListBuilders.buildListOfAtLeastTwo(first, second, more), - new ConfiguredEqualsVerifier() - ); + public static MultipleTypeEqualsVerifierApi forClasses(Class first, Class second, Class... more) { + return new MultipleTypeEqualsVerifierApi(ListBuilders.buildListOfAtLeastTwo(first, second, more), + new ConfiguredEqualsVerifier()); } /** * Factory method. For general use. * - *

Note that this operation may be slow. If the test is too slow, use {@link - * #forClasses(Class, Class, Class...)} instead. + *

+ * Note that this operation may be slow. If the test is too slow, use {@link #forClasses(Class, Class, Class...)} + * instead. * * @param packageName A package for which each class's {@code equals} should be tested. * @return A fluent API for EqualsVerifier. @@ -119,17 +115,15 @@ public static MultipleTypeEqualsVerifierApi forPackage(String packageName) { /** * Factory method. For general use. * - *

Note that this operation may be slow. If the test is too slow, use {@link - * #forClasses(Class, Class, Class...)} instead. + *

+ * Note that this operation may be slow. If the test is too slow, use {@link #forClasses(Class, Class, Class...)} + * instead. * - * @param packageName A package for which each class's {@code equals} should be tested. + * @param packageName A package for which each class's {@code equals} should be tested. * @param scanRecursively true to scan all sub-packages * @return A fluent API for EqualsVerifier. */ - public static MultipleTypeEqualsVerifierApi forPackage( - String packageName, - boolean scanRecursively - ) { + public static MultipleTypeEqualsVerifierApi forPackage(String packageName, boolean scanRecursively) { List> classes = PackageScanner.getClassesIn(packageName, null, scanRecursively); Validations.validatePackageContainsClasses(packageName, classes); return new MultipleTypeEqualsVerifierApi(classes, new ConfiguredEqualsVerifier()); @@ -138,20 +132,18 @@ public static MultipleTypeEqualsVerifierApi forPackage( /** * Factory method. For general use. * - *

Note that this operation may be slow. If the test is too slow, use {@link - * #forClasses(Class, Class, Class...)} instead. + *

+ * Note that this operation may be slow. If the test is too slow, use {@link #forClasses(Class, Class, Class...)} + * instead. * - *

Also note that if {@code mustExtend} is given, and it exists within {@code packageName}, - * it will NOT be included. + *

+ * Also note that if {@code mustExtend} is given, and it exists within {@code packageName}, it will NOT be included. * * @param packageName A package for which each class's {@code equals} should be tested. - * @param mustExtend if not null, returns only classes that extend or implement this class. + * @param mustExtend if not null, returns only classes that extend or implement this class. * @return A fluent API for EqualsVerifier. */ - public static MultipleTypeEqualsVerifierApi forPackage( - String packageName, - Class mustExtend - ) { + public static MultipleTypeEqualsVerifierApi forPackage(String packageName, Class mustExtend) { List> classes = PackageScanner.getClassesIn(packageName, mustExtend, true); Validations.validatePackageContainsClasses(packageName, classes); return new MultipleTypeEqualsVerifierApi(classes, new ConfiguredEqualsVerifier()); @@ -160,31 +152,30 @@ public static MultipleTypeEqualsVerifierApi forPackage( /** * Factory method. Asks for a list of equal, but not identical, instances of T. * - *

For use when T is a class which has relaxed equality rules. This happens when two - * instances of T are equal even though the its internal state is different. + *

+ * For use when T is a class which has relaxed equality rules. This happens when two instances of T are equal even + * though the its internal state is different. * - *

This could happen, for example, in a Rational class that doesn't normalize: new - * Rational(1, 2).equals(new Rational(2, 4)) would return true. + *

+ * This could happen, for example, in a Rational class that doesn't normalize: new Rational(1, 2).equals(new + * Rational(2, 4)) would return true. * - *

Using this factory method requires that {@link - * RelaxedEqualsVerifierApi#andUnequalExamples(Object, Object...)} be called to supply a list of - * unequal instances of T. + *

+ * Using this factory method requires that {@link RelaxedEqualsVerifierApi#andUnequalExamples(Object, Object...)} be + * called to supply a list of unequal instances of T. * - *

This method automatically suppresses {@link Warning#ALL_FIELDS_SHOULD_BE_USED}. + *

+ * This method automatically suppresses {@link Warning#ALL_FIELDS_SHOULD_BE_USED}. * - * @param first An instance of T. + * @param first An instance of T. * @param second Another instance of T, which is equal, but not identical, to {@code first}. - * @param more More instances of T, all of which are equal, but not identical, to one another - * and to {@code first} and {@code second}. - * @param the type. + * @param more More instances of T, all of which are equal, but not identical, to one another and to {@code first} + * and {@code second}. + * @param the type. * @return A fluent API for a more relaxed EqualsVerifier. */ @SafeVarargs - public static RelaxedEqualsVerifierApi forRelaxedEqualExamples( - T first, - T second, - T... more - ) { + public static RelaxedEqualsVerifierApi forRelaxedEqualExamples(T first, T second, T... more) { List examples = ListBuilders.buildListOfAtLeastTwo(first, second, more); @SuppressWarnings("unchecked") diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/EqualsVerifierReport.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/EqualsVerifierReport.java index 6fb507982..2b1751247 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/EqualsVerifierReport.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/EqualsVerifierReport.java @@ -6,9 +6,10 @@ /** * Contains the results of an {@link nl.jqno.equalsverifier.EqualsVerifier} run. * - *

When the run was successful, should contain an empty message and a null cause. When the run - * was unsuccessful, the message is identical to the message of the exception that {@link - * SingleTypeEqualsVerifierApi#verify()} would throw, and the cause would be identical to its cause. + *

+ * When the run was successful, should contain an empty message and a null cause. When the run was unsuccessful, the + * message is identical to the message of the exception that {@link SingleTypeEqualsVerifierApi#verify()} would throw, + * and the cause would be identical to its cause. */ public final class EqualsVerifierReport { @@ -31,9 +32,9 @@ public static EqualsVerifierReport success(Class type) { /** * Factory method for an unsuccessful run of {@code EqualsVerifier}. * - * @param type The class that was tested. + * @param type The class that was tested. * @param message Error message when the run is unsuccessful. - * @param cause Exception when the run is unsuccessful. + * @param cause Exception when the run is unsuccessful. * @return an {@code EqualsVerifierReport} representing the failed result of a run of {@code * EqualsVerifier}. */ @@ -42,12 +43,7 @@ public static EqualsVerifierReport failure(Class type, String message, Throwa } /** Private constructor. Use {@link #SUCCESS} or {@link #failure(String, Throwable)} instead. */ - private EqualsVerifierReport( - Class type, - boolean successful, - String message, - Throwable cause - ) { + private EqualsVerifierReport(Class type, boolean successful, String message, Throwable cause) { this.type = type; this.successful = successful; this.message = message; @@ -60,32 +56,28 @@ public Class getType() { } /** - * @return whether the class tested by {@link SingleTypeEqualsVerifierApi#report()} conforms to - * the {@link Object#equals(Object)} and {@link Object#hashCode()} contracts. + * @return whether the class tested by {@link SingleTypeEqualsVerifierApi#report()} conforms to the + * {@link Object#equals(Object)} and {@link Object#hashCode()} contracts. */ public boolean isSuccessful() { return successful; } /** - * @return a detailed error message if the class tested by {@link - * SingleTypeEqualsVerifierApi#report()} does not conform to the {@link - * Object#equals(Object)} and {@link Object#hashCode()} contracts; or an empty string if it - * does. + * @return a detailed error message if the class tested by {@link SingleTypeEqualsVerifierApi#report()} does not + * conform to the {@link Object#equals(Object)} and {@link Object#hashCode()} contracts; or an empty + * string if it does. */ public String getMessage() { return message; } /** - * @return an exception indicating the source of the failure if the class tested by {@link - * SingleTypeEqualsVerifierApi#report()} does not conform to the {@link - * Object#equals(Object)} and {@link Object#hashCode()} contracts; or null if it does. + * @return an exception indicating the source of the failure if the class tested by + * {@link SingleTypeEqualsVerifierApi#report()} does not conform to the {@link Object#equals(Object)} + * and {@link Object#hashCode()} contracts; or null if it does. */ - @SuppressFBWarnings( - value = "EI_EXPOSE_REP", - justification = "Can't defensively copy a Throwable." - ) + @SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "Can't defensively copy a Throwable.") public Throwable getCause() { return cause; } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/Func.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/Func.java index e5f6115f1..bd4fd646d 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/Func.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/Func.java @@ -5,8 +5,9 @@ /** * Functional interface for generating prefab values of some generic type {@code T}. * - *

For each generic type parameter for {@code T}, a value of that type will be supplied in the - * {@link List} parameter of {@link Func#apply(List)}. + *

+ * For each generic type parameter for {@code T}, a value of that type will be supplied in the {@link List} parameter of + * {@link Func#apply(List)}. * * @param The type of prefab value. */ @@ -15,10 +16,11 @@ public interface Func { T apply(List values); /** - * Functional interface for generating prefab values of a generic type {@code T} that has - * exactly 1 generic parameter {@code A}. + * Functional interface for generating prefab values of a generic type {@code T} that has exactly 1 generic + * parameter {@code A}. * - *

A value of {@link A} will be supplied in the {@link Func1#supply(Object)} method. + *

+ * A value of {@link A} will be supplied in the {@link Func1#supply(Object)} method. * * @param The type of {@code T}'s generic parameter. * @param The type of prefab value. @@ -35,11 +37,11 @@ default T apply(List values) { } /** - * Functional interface for generating prefab values of a generic type {@code T} that has - * exactly 2 generic parameters, {@code A} and {@code B}. + * Functional interface for generating prefab values of a generic type {@code T} that has exactly 2 generic + * parameters, {@code A} and {@code B}. * - *

Values of {@link A} and {@code B} will be supplied in the {@link Func2#supply(Object, - * Object)} method. + *

+ * Values of {@link A} and {@code B} will be supplied in the {@link Func2#supply(Object, Object)} method. * * @param The type of {@code T}'s first generic parameter. * @param The type of {@code T}'s second generic parameter. diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/Warning.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/Warning.java index 7d151f2a9..c6fb0f720 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/Warning.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/Warning.java @@ -13,108 +13,119 @@ public enum Warning { * EqualsVerifier} will not fail if one or more fields do not affect the outcome of {@code * equals}. * - *

Only applies to non-transient fields. + *

+ * Only applies to non-transient fields. */ ALL_FIELDS_SHOULD_BE_USED, /** * Signals that non-final fields are not relevant in the {@code equals} contract. {@code - * EqualsVerifier} will not fail if one or more non-final fields do not affect the outcome of - * {@code equals}. + * EqualsVerifier} will not fail if one or more non-final fields do not affect the outcome of {@code equals}. * - *

Only applies to non-transient fields. + *

+ * Only applies to non-transient fields. */ ALL_NONFINAL_FIELDS_SHOULD_BE_USED, /** * Disables the check for reference equality on fields. * - *

EqualsVerifier will check if the {@code equals} method calls equals on the object fields - * of the class under test, instead of the {@code ==} operator, since normally this signifies a - * mistake (e.g. comparing string fields with {@code ==}). + *

+ * EqualsVerifier will check if the {@code equals} method calls equals on the object fields of the class under test, + * instead of the {@code ==} operator, since normally this signifies a mistake (e.g. comparing string fields with + * {@code ==}). * - *

However, sometimes {@code ==} is used intentionally, or the field in question doesn't - * implement {@code equals} itself, so a call to the {@code equals} method of that field is - * essentially a reference equality check instead of a value equality check. In these cases, - * this warning can be suppressed. + *

+ * However, sometimes {@code ==} is used intentionally, or the field in question doesn't implement {@code equals} + * itself, so a call to the {@code equals} method of that field is essentially a reference equality check instead of + * a value equality check. In these cases, this warning can be suppressed. */ REFERENCE_EQUALITY, /** - * Disables the check, when the {@code equals} method is overridden in the class under test, - * that an instance of this class should be equal to an identical copy of itself. + * Disables the check, when the {@code equals} method is overridden in the class under test, that an instance of + * this class should be equal to an identical copy of itself. * - *

Normally, it is important that an object be equal to an identical copy of itself: after - * all, this is the point of overriding {@code equals} in the first place. + *

+ * Normally, it is important that an object be equal to an identical copy of itself: after all, this is the point of + * overriding {@code equals} in the first place. * - *

However, when the class is part of a hierarchy, but should be (pseudo-)singleton, it can - * be useful to suppress this warning. This can happen in certain implementations of the Null - * Object Pattern, for example. + *

+ * However, when the class is part of a hierarchy, but should be (pseudo-)singleton, it can be useful to suppress + * this warning. This can happen in certain implementations of the Null Object Pattern, for example. * - *

If this warning is suppressed, and it turns out that an instance of the class under test - * is equal to an identical copy of itself after all, {@link EqualsVerifier} will fail. + *

+ * If this warning is suppressed, and it turns out that an instance of the class under test is equal to an identical + * copy of itself after all, {@link EqualsVerifier} will fail. */ IDENTICAL_COPY, /** - * Disables the check, when the {@code equals} method is overridden in the class under test, - * that an instance of this class should be equal to an identical copy of itself. + * Disables the check, when the {@code equals} method is overridden in the class under test, that an instance of + * this class should be equal to an identical copy of itself. * - *

Normally, it is important that an object be equal to an identical copy of itself: after - * all, this is the point of overriding {@code equals} in the first place. + *

+ * Normally, it is important that an object be equal to an identical copy of itself: after all, this is the point of + * overriding {@code equals} in the first place. * - *

However, when the class is a kind of versioned entity and there is an {@code id} field - * that is zero when the object is new, it is often the case that two new objects are never - * equal to each other. In these cases, it can be useful to suppress this warning. + *

+ * However, when the class is a kind of versioned entity and there is an {@code id} field that is zero when the + * object is new, it is often the case that two new objects are never equal to each other. In these cases, it can be + * useful to suppress this warning. * - *

You cannot use {@link #IDENTICAL_COPY} in these cases, because when the {@code id}s are - * equal, the objects should be, too, and {@link EqualsVerifier} would fail in this case. + *

+ * You cannot use {@link #IDENTICAL_COPY} in these cases, because when the {@code id}s are equal, the objects should + * be, too, and {@link EqualsVerifier} would fail in this case. * - *

If this warning is suppressed, and it turns out that an instance of the class under test - * is equal to an identical copy of itself after all, {@link EqualsVerifier} will NOT fail. + *

+ * If this warning is suppressed, and it turns out that an instance of the class under test is equal to an identical + * copy of itself after all, {@link EqualsVerifier} will NOT fail. */ IDENTICAL_COPY_FOR_VERSIONED_ENTITY, /** * Disables the check that verifies {@code equals} is actually overridden. * - *

Can be used when a whole package of classes is automatically scanned and presented to - * EqualsVerifier, and one or more of them don't need to override {@code equals}. + *

+ * Can be used when a whole package of classes is automatically scanned and presented to EqualsVerifier, and one or + * more of them don't need to override {@code equals}. */ INHERITED_DIRECTLY_FROM_OBJECT, /** * Disables the example check for cached {@code hashCode}. * - *

The example check verifies that the cached {@code hashCode} is properly initialized. You - * can use this, if creating an example object is too cumbersome. In this case, null can be - * passed as an example. + *

+ * The example check verifies that the cached {@code hashCode} is properly initialized. You can use this, if + * creating an example object is too cumbersome. In this case, null can be passed as an example. * - *

Note that suppressing this warning can be dangerous and should only be done in unusual - * circumstances. + *

+ * Note that suppressing this warning can be dangerous and should only be done in unusual circumstances. */ NO_EXAMPLE_FOR_CACHED_HASHCODE, /** * Disables checks for non-final fields on which {@code equals} and {@code hashCode} depend. * - *

{@link EqualsVerifier}'s standard behaviour is to disallow non-final fields being used in - * {@code equals} and {@code hashCode} methods, since classes that depend on non-final fields in - * these methods cannot reliably be used in collections. + *

+ * {@link EqualsVerifier}'s standard behaviour is to disallow non-final fields being used in {@code equals} and + * {@code hashCode} methods, since classes that depend on non-final fields in these methods cannot reliably be used + * in collections. * - *

However, sometimes an external library requires that fields be non-final. An example of - * this are Java Beans. In such a case, suppress this warning to prevent {@link EqualsVerifier} - * from checking for non-final fields. + *

+ * However, sometimes an external library requires that fields be non-final. An example of this are Java Beans. In + * such a case, suppress this warning to prevent {@link EqualsVerifier} from checking for non-final fields. */ NONFINAL_FIELDS, /** - * Disables checks for {@link NullPointerException} within {@code equals}, {@code hashCode} and - * {@code toString} methods. + * Disables checks for {@link NullPointerException} within {@code equals}, {@code hashCode} and {@code toString} + * methods. * - *

Sometimes the constructor of a class makes sure no field can be null. If this is the case, - * and if the fields cannot be made null later in the lifecycle of the class by setters or other - * methods, suppress this warning to disable the check for {@link NullPointerException}. + *

+ * Sometimes the constructor of a class makes sure no field can be null. If this is the case, and if the fields + * cannot be made null later in the lifecycle of the class by setters or other methods, suppress this warning to + * disable the check for {@link NullPointerException}. */ NULL_FIELDS, @@ -122,88 +133,93 @@ public enum Warning { * Disables the check that all fields used in {@code equals} must also be used in {@code * hashCode}. * - *

This is useful when bringing legacy systems under test, where you don't want to change the - * existing {@code hashCode} behaviour but you do want to use EqualsVerifier. + *

+ * This is useful when bringing legacy systems under test, where you don't want to change the existing + * {@code hashCode} behaviour but you do want to use EqualsVerifier. * - *

Note that {@code hashCode}s with higher distributions give better performance when used in - * collections such as {@link java.util.HashMap}. Therefore, if possible, you should use all - * fields that are used in {@code equals}, in {@code hashCode} as well. + *

+ * Note that {@code hashCode}s with higher distributions give better performance when used in collections such as + * {@link java.util.HashMap}. Therefore, if possible, you should use all fields that are used in {@code equals}, in + * {@code hashCode} as well. */ STRICT_HASHCODE, /** * Disables some of the stricter inheritance tests. * - *

{@link EqualsVerifier}'s standard behaviour, if T is not final and neither are its {@code - * equals} and {@code hashCode} methods, is to require a reference to a subclass of T for which - * no instance can be equal to any instance of T, to make sure that subclasses that can redefine - * {@code equals} or {@code hashCode} don't break the contract; or it asks to call the {@code - * usingGetClass} method if T uses {@code getClass()} instead of {@code instanceof} in its - * {@code equals} method. + *

+ * {@link EqualsVerifier}'s standard behaviour, if T is not final and neither are its {@code + * equals} and {@code hashCode} methods, is to require a reference to a subclass of T for which no instance can be + * equal to any instance of T, to make sure that subclasses that can redefine {@code equals} or {@code hashCode} + * don't break the contract; or it asks to call the {@code + * usingGetClass} method if T uses {@code getClass()} instead of {@code instanceof} in its {@code equals} method. * - *

Some may find that too strict for their liking; suppressing this warning disables that - * test. + *

+ * Some may find that too strict for their liking; suppressing this warning disables that test. * * @see nl.jqno.equalsverifier.api.SingleTypeEqualsVerifierApi#withRedefinedSubclass(Class) */ STRICT_INHERITANCE, /** - * Disables the check that fields marked with the @Id or @EmbeddedId annotations in JPA entities - * may not be used in the {@code equals} contract. + * Disables the check that fields marked with the @Id or @EmbeddedId annotations in JPA entities may not be used in + * the {@code equals} contract. * - *

When this warning is suppressed, the fields marked with @Id or @EmbeddedId will become the - * entity's surrogate key. Only these fields can now be part of the {@code equals} contract; all - * other fields may no longer be used in {@code equals}. + *

+ * When this warning is suppressed, the fields marked with @Id or @EmbeddedId will become the entity's surrogate + * key. Only these fields can now be part of the {@code equals} contract; all other fields may no longer be used in + * {@code equals}. */ SURROGATE_KEY, /** - * Disables the check that fields marked with the @Id or @EmbeddedId annotations in JPA entities - * may not be used in the {@code equals} contract. + * Disables the check that fields marked with the @Id or @EmbeddedId annotations in JPA entities may not be used in + * the {@code equals} contract. * - *

When this warning is suppressed, all fields will become part of the entity's key, and - * EqualsVerifier will operate as if the entity were a normal class. + *

+ * When this warning is suppressed, all fields will become part of the entity's key, and EqualsVerifier will operate + * as if the entity were a normal class. */ SURROGATE_OR_BUSINESS_KEY, /** - * Disables the check that collection fields in JPA, or @Basic fields marked with - * FetchType.LAZY, should be accessed through their getter methods in {@code equals} and - * {@code hashCode} methods. + * Disables the check that collection fields in JPA, or @Basic fields marked with FetchType.LAZY, should be accessed + * through their getter methods in {@code equals} and {@code hashCode} methods. * - *

Normally, it is necessary to go through the getter for these fields, because their - * content may not be materialized in some instances. Calling the getter will materialize them, - * but referencing the field directly will not. This can lead to situations where the - * {@code equals} method of objects that should be equal to each other returns false, because - * one instance has the content materialized and the other does not. + *

+ * Normally, it is necessary to go through the getter for these fields, because their content may not be + * materialized in some instances. Calling the getter will materialize them, but referencing the field directly will + * not. This can lead to situations where the {@code equals} method of objects that should be equal to each other + * returns false, because one instance has the content materialized and the other does not. */ JPA_GETTER, /** * Disables the check that transient fields not be part of the {@code equals} contract. * - *

{@link EqualsVerifier}'s standard behaviour is to disallow transient fields being used in - * {@code equals} and {@code hashCode} methods, since these fields may not be restored to their - * original state after deserialization, which would break {@code equals}. + *

+ * {@link EqualsVerifier}'s standard behaviour is to disallow transient fields being used in {@code equals} and + * {@code hashCode} methods, since these fields may not be restored to their original state after deserialization, + * which would break {@code equals}. * - *

If measures are taken that this will never happen, this warning can be suppressed to - * disable {@link EqualsVerifier}'s transience test. + *

+ * If measures are taken that this will never happen, this warning can be suppressed to disable + * {@link EqualsVerifier}'s transience test. */ TRANSIENT_FIELDS, /** - * Disables the check that equality of {@code BigDecimal} fields is implemented using - * {@code compareTo} rather than {@code equals}. + * Disables the check that equality of {@code BigDecimal} fields is implemented using {@code compareTo} rather than + * {@code equals}. * - *

{@code BigDecimal} objects that are equal using {@code compareTo} are not necessarily - * equal using {@code equals}, for example the values of {@literal 1} and {@literal 1.0}. - * For variants of the same value to be considered equal, classes with {@code BigDecimal} - * fields should use {@code compareTo} to check equality of non-null {@code BigDecimal} - * references and produce the same hashcode for all equal variants. + *

+ * {@code BigDecimal} objects that are equal using {@code compareTo} are not necessarily equal using {@code equals}, + * for example the values of {@literal 1} and {@literal 1.0}. For variants of the same value to be considered equal, + * classes with {@code BigDecimal} fields should use {@code compareTo} to check equality of non-null + * {@code BigDecimal} references and produce the same hashcode for all equal variants. * - *

{@code EqualsVerifier} checks for this by default but it can be disabled by suppressing - * this warning. + *

+ * {@code EqualsVerifier} checks for this by default but it can be disabled by suppressing this warning. */ BIGDECIMAL_EQUALITY, diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/api/EqualsVerifierApi.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/api/EqualsVerifierApi.java index fbb3e9491..6fc65128f 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/api/EqualsVerifierApi.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/api/EqualsVerifierApi.java @@ -1,6 +1,7 @@ package nl.jqno.equalsverifier.api; import java.util.function.Function; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Func.Func1; import nl.jqno.equalsverifier.Func.Func2; @@ -13,8 +14,7 @@ */ public interface EqualsVerifierApi { /** - * Suppresses warnings given by {@code EqualsVerifier}. See {@link Warning} to see what warnings - * can be suppressed. + * Suppresses warnings given by {@code EqualsVerifier}. See {@link Warning} to see what warnings can be suppressed. * * @param warnings A list of warnings to suppress in {@code EqualsVerifier}. * @return {@code this}, for easy method chaining. @@ -22,49 +22,46 @@ public interface EqualsVerifierApi { EqualsVerifierApi suppress(Warning... warnings); /** - * Adds prefabricated values for instance fields of classes that EqualsVerifier cannot - * instantiate by itself. + * Adds prefabricated values for instance fields of classes that EqualsVerifier cannot instantiate by itself. * - * @param The class of the prefabricated values. + * @param The class of the prefabricated values. * @param otherType The class of the prefabricated values. - * @param red An instance of {@code S}. - * @param blue Another instance of {@code S}, not equal to {@code red}. + * @param red An instance of {@code S}. + * @param blue Another instance of {@code S}, not equal to {@code red}. * @return {@code this}, for easy method chaining. - * @throws NullPointerException If either {@code otherType}, {@code red}, or {@code blue} is - * null. + * @throws NullPointerException If either {@code otherType}, {@code red}, or {@code blue} is null. * @throws IllegalArgumentException If {@code red} equals {@code blue}. */ EqualsVerifierApi withPrefabValues(Class otherType, S red, S blue); /** - * Adds a factory to generate prefabricated values for instance fields of classes with 1 generic - * type parameter that EqualsVerifier cannot instantiate by itself. + * Adds a factory to generate prefabricated values for instance fields of classes with 1 generic type parameter that + * EqualsVerifier cannot instantiate by itself. * - * @param The class of the prefabricated values. + * @param The class of the prefabricated values. * @param otherType The class of the prefabricated values. - * @param factory A factory to generate an instance of {@code S}, given a value of its generic - * type parameter. + * @param factory A factory to generate an instance of {@code S}, given a value of its generic type parameter. * @return {@code this}, for easy method chaining. * @throws NullPointerException if either {@code otherType} or {@code factory} is null. */ EqualsVerifierApi withGenericPrefabValues(Class otherType, Func1 factory); /** - * Adds a factory to generate prefabricated values for instance fields of classes with 2 generic - * type parameters that EqualsVerifier cannot instantiate by itself. + * Adds a factory to generate prefabricated values for instance fields of classes with 2 generic type parameters + * that EqualsVerifier cannot instantiate by itself. * - * @param The class of the prefabricated values. + * @param The class of the prefabricated values. * @param otherType The class of the prefabricated values. - * @param factory A factory to generate an instance of {@code S}, given a value of each of its - * generic type parameters. + * @param factory A factory to generate an instance of {@code S}, given a value of each of its generic type + * parameters. * @return {@code this}, for easy method chaining. * @throws NullPointerException if either {@code otherType} or {@code factory} is null. */ EqualsVerifierApi withGenericPrefabValues(Class otherType, Func2 factory); /** - * Signals that {@code getClass} is used in the implementation of the {@code equals} method, - * instead of an {@code instanceof} check. + * Signals that {@code getClass} is used in the implementation of the {@code equals} method, instead of an + * {@code instanceof} check. * * @return {@code this}, for easy method chaining. * @see Warning#STRICT_INHERITANCE @@ -74,8 +71,8 @@ public interface EqualsVerifierApi { /** * Determines how a getter name can be derived from a field name. * - * The default behavior is to uppercase the field's first letter and prepend 'get'. For - * instance, a field name 'employee' would correspond to getter name 'getEmployee'. + * The default behavior is to uppercase the field's first letter and prepend 'get'. For instance, a field name + * 'employee' would correspond to getter name 'getEmployee'. * * This method can be used if your project has a different naming convention. * @@ -85,9 +82,9 @@ public interface EqualsVerifierApi { EqualsVerifierApi withFieldnameToGetterConverter(Function converter); /** - * Signals that all internal caches need to be reset. This is useful when the test framework - * uses multiple ClassLoaders to run tests, causing {@link java.lang.Class} instances - * that would normally be equal, to be unequal, because their ClassLoaders don't match. + * Signals that all internal caches need to be reset. This is useful when the test framework uses multiple + * ClassLoaders to run tests, causing {@link java.lang.Class} instances that would normally be equal, to be unequal, + * because their ClassLoaders don't match. * * @return {@code this}, for easy method chaining. * @deprecated No longer needed; this happens automatically. diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/api/MultipleTypeEqualsVerifierApi.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/api/MultipleTypeEqualsVerifierApi.java index ecb285619..dcd593684 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/api/MultipleTypeEqualsVerifierApi.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/api/MultipleTypeEqualsVerifierApi.java @@ -5,6 +5,7 @@ import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; + import nl.jqno.equalsverifier.ConfiguredEqualsVerifier; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.EqualsVerifierReport; @@ -45,20 +46,14 @@ public MultipleTypeEqualsVerifierApi withPrefabValues(Class otherType, S /** {@inheritDoc} */ @Override - public MultipleTypeEqualsVerifierApi withGenericPrefabValues( - Class otherType, - Func1 factory - ) { + public MultipleTypeEqualsVerifierApi withGenericPrefabValues(Class otherType, Func1 factory) { ev.withGenericPrefabValues(otherType, factory); return this; } /** {@inheritDoc} */ @Override - public MultipleTypeEqualsVerifierApi withGenericPrefabValues( - Class otherType, - Func2 factory - ) { + public MultipleTypeEqualsVerifierApi withGenericPrefabValues(Class otherType, Func2 factory) { ev.withGenericPrefabValues(otherType, factory); return this; } @@ -72,15 +67,14 @@ public MultipleTypeEqualsVerifierApi usingGetClass() { /** {@inheritDoc} */ @Override - public MultipleTypeEqualsVerifierApi withFieldnameToGetterConverter( - Function converter - ) { + public MultipleTypeEqualsVerifierApi withFieldnameToGetterConverter(Function converter) { ev.withFieldnameToGetterConverter(converter); return this; } /** * {@inheritDoc} + * * @deprecated No longer needed; this happens automatically. */ @Deprecated @@ -105,15 +99,11 @@ public MultipleTypeEqualsVerifierApi except(Class type, Class... more) { /** * Removes all types matching the given Predicate. * - * @param exclusionPredicate A Predicate matching classes to remove from the list of types to - * verify. + * @param exclusionPredicate A Predicate matching classes to remove from the list of types to verify. * @return {@code this}, for easy method chaining. */ public MultipleTypeEqualsVerifierApi except(Predicate> exclusionPredicate) { - List> typesToRemove = types - .stream() - .filter(exclusionPredicate) - .collect(Collectors.toList()); + List> typesToRemove = types.stream().filter(exclusionPredicate).collect(Collectors.toList()); removeTypes(typesToRemove); return this; } @@ -124,42 +114,36 @@ private void removeTypes(List> typesToRemove) { } /** - * Performs the verification of the contracts for {@code equals} and {@code hashCode} and throws - * an {@link AssertionError} if there is a problem. + * Performs the verification of the contracts for {@code equals} and {@code hashCode} and throws an + * {@link AssertionError} if there is a problem. * - * @throws AssertionError If one of the contracts is not met, or if {@link EqualsVerifier}'s - * preconditions do not hold. + * @throws AssertionError If one of the contracts is not met, or if {@link EqualsVerifier}'s preconditions do not + * hold. */ public void verify() { - List failures = report() - .stream() - .filter(r -> !r.isSuccessful()) - .collect(Collectors.toList()); + List failures = + report().stream().filter(r -> !r.isSuccessful()).collect(Collectors.toList()); if (failures.isEmpty()) { return; } String messages = Formatter - .of( - "EqualsVerifier found a problem in %% %%.\n---\n%%\n---\n%%\n---\n%%", - failures.size(), - failures.size() == 1 ? "class" : "classes", - failures - .stream() - .map(r -> "* " + r.getType().getName()) - .collect(Collectors.joining("\n")), - failures.stream().map(r -> r.getMessage()).collect(Collectors.joining("\n---\n")), - ErrorMessage.suffix() - ) - .format(); + .of( + "EqualsVerifier found a problem in %% %%.\n---\n%%\n---\n%%\n---\n%%", + failures.size(), + failures.size() == 1 ? "class" : "classes", + failures.stream().map(r -> "* " + r.getType().getName()).collect(Collectors.joining("\n")), + failures.stream().map(r -> r.getMessage()).collect(Collectors.joining("\n---\n")), + ErrorMessage.suffix()) + .format(); throw new AssertionError(messages); } /** - * Performs the verifications of the contracts for {@code equals} and {@code hashCode} and - * returns a List of {@link EqualsVerifierReport} with the results of the verifications. + * Performs the verifications of the contracts for {@code equals} and {@code hashCode} and returns a List of + * {@link EqualsVerifierReport} with the results of the verifications. * - * @return A List of {@link EqualsVerifierReport} that indicates whether the contracts are met - * and whether {@link EqualsVerifier}'s preconditions hold. + * @return A List of {@link EqualsVerifierReport} that indicates whether the contracts are met and whether + * {@link EqualsVerifier}'s preconditions hold. */ public List report() { return types.stream().map(t -> ev.forClass(t).report(false)).collect(Collectors.toList()); diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/api/RelaxedEqualsVerifierApi.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/api/RelaxedEqualsVerifierApi.java index c52eac1b8..9eff0f600 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/api/RelaxedEqualsVerifierApi.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/api/RelaxedEqualsVerifierApi.java @@ -4,14 +4,15 @@ import java.util.Collections; import java.util.List; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.util.Validations; /** - * API class for {@link EqualsVerifier#forRelaxedEqualExamples(Object, Object, Object...)}. Its - * purpose is to make sure, at compile time, that a list of unequal examples is given, as well as - * the list of equal examples that are supplied to the aforementioned method. + * API class for {@link EqualsVerifier#forRelaxedEqualExamples(Object, Object, Object...)}. Its purpose is to make sure, + * at compile time, that a list of unequal examples is given, as well as the list of equal examples that are supplied to + * the aforementioned method. */ public class RelaxedEqualsVerifierApi { @@ -21,7 +22,7 @@ public class RelaxedEqualsVerifierApi { /** * Constructor. * - * @param type The class for which the {@code equals} method should be tested. + * @param type The class for which the {@code equals} method should be tested. * @param examples A list of example instances that are equal but not identical to one another. */ public RelaxedEqualsVerifierApi(Class type, List examples) { @@ -41,13 +42,12 @@ public SingleTypeEqualsVerifierApi andUnequalExample(T example) { } /** - * Asks for a list of unequal instances of T and subsequently returns a fully constructed - * instance of {@link EqualsVerifier}. + * Asks for a list of unequal instances of T and subsequently returns a fully constructed instance of + * {@link EqualsVerifier}. * * @param first An instance of T that is unequal to the previously supplied equal examples. - * @param more More instances of T, all of which are unequal to one another, to {@code first}, - * and to the previously supplied equal examples. May also contain instances of subclasses - * of T. + * @param more More instances of T, all of which are unequal to one another, to {@code first}, and to the + * previously supplied equal examples. May also contain instances of subclasses of T. * @return An instance of {@link EqualsVerifier}. */ @SafeVarargs @@ -55,6 +55,6 @@ public final SingleTypeEqualsVerifierApi andUnequalExamples(T first, T... mor List unequalExamples = buildListOfAtLeastOne(first, more); Validations.validateUnequalExamples(unequalExamples, equalExamples); return new SingleTypeEqualsVerifierApi<>(type, equalExamples, unequalExamples) - .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED); + .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED); } } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/api/SingleTypeEqualsVerifierApi.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/api/SingleTypeEqualsVerifierApi.java index e87acdac8..0967c5d1b 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/api/SingleTypeEqualsVerifierApi.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/api/SingleTypeEqualsVerifierApi.java @@ -2,6 +2,7 @@ import java.util.*; import java.util.function.Function; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.EqualsVerifierReport; import nl.jqno.equalsverifier.Func.Func1; @@ -33,8 +34,7 @@ public class SingleTypeEqualsVerifierApi implements EqualsVerifierApi { private Class redefinedSubclass = null; private FactoryCache factoryCache = new FactoryCache(); private FieldCache fieldCache = new FieldCache(); - private CachedHashCodeInitializer cachedHashCodeInitializer = - CachedHashCodeInitializer.passthrough(); + private CachedHashCodeInitializer cachedHashCodeInitializer = CachedHashCodeInitializer.passthrough(); private Function fieldnameToGetter = null; private Set allExcludedFields = new HashSet<>(); private Set allIncludedFields = new HashSet<>(); @@ -56,7 +56,7 @@ public SingleTypeEqualsVerifierApi(Class type) { /** * Constructor. * - * @param type The class for which the {@code equals} method should be tested. + * @param type The class for which the {@code equals} method should be tested. * @param objenesis To instantiate non-record classes. */ public SingleTypeEqualsVerifierApi(Class type, Objenesis objenesis) { @@ -68,22 +68,21 @@ public SingleTypeEqualsVerifierApi(Class type, Objenesis objenesis) { /** * Constructor. * - * @param type The class for which the {@code equals} method should be tested. + * @param type The class for which the {@code equals} method should be tested. * @param warningsToSuppress A list of warnings to suppress in {@code EqualsVerifier}. - * @param factoryCache Factories that can be used to create values. - * @param objenesis To instantiate non-record classes. - * @param usingGetClass Whether {@code getClass} is used in the implementation of the {@code - * equals} method, instead of an {@code instanceof} check. - * @param converter A function that converts from field name to getter name. + * @param factoryCache Factories that can be used to create values. + * @param objenesis To instantiate non-record classes. + * @param usingGetClass Whether {@code getClass} is used in the implementation of the {@code + * equals} method, instead of an {@code instanceof} check. + * @param converter A function that converts from field name to getter name. */ public SingleTypeEqualsVerifierApi( - Class type, - EnumSet warningsToSuppress, - FactoryCache factoryCache, - Objenesis objenesis, - boolean usingGetClass, - Function converter - ) { + Class type, + EnumSet warningsToSuppress, + FactoryCache factoryCache, + Objenesis objenesis, + boolean usingGetClass, + Function converter) { this(type, objenesis); this.warningsToSuppress = EnumSet.copyOf(warningsToSuppress); this.factoryCache = this.factoryCache.merge(factoryCache); @@ -92,14 +91,9 @@ public SingleTypeEqualsVerifierApi( } /** - * Constructor, only to be called by {@link RelaxedEqualsVerifierApi#andUnequalExamples(Object, - * Object[])}. + * Constructor, only to be called by {@link RelaxedEqualsVerifierApi#andUnequalExamples(Object, Object[])}. */ - /* package protected */SingleTypeEqualsVerifierApi( - Class type, - List equalExamples, - List unequalExamples - ) { + /* package protected */ SingleTypeEqualsVerifierApi(Class type, List equalExamples, List unequalExamples) { this(type, new ObjenesisStd()); this.equalExamples = equalExamples; this.unequalExamples = unequalExamples; @@ -110,11 +104,7 @@ public SingleTypeEqualsVerifierApi( public SingleTypeEqualsVerifierApi suppress(Warning... warnings) { Collections.addAll(warningsToSuppress, warnings); Validations.validateWarnings(warningsToSuppress); - Validations.validateWarningsAndFields( - warningsToSuppress, - allIncludedFields, - allExcludedFields - ); + Validations.validateWarningsAndFields(warningsToSuppress, allIncludedFields, allExcludedFields); Validations.validateNonnullFields(nonnullFields, warningsToSuppress); return this; } @@ -127,23 +117,19 @@ public SingleTypeEqualsVerifierApi withPrefabValues(Class otherType, S } /** - * Adds prefabricated values for instance fields with a given name (and only the fields with - * the given name) that EqualsVerifier cannot instantiate by itself. + * Adds prefabricated values for instance fields with a given name (and only the fields with the given name) that + * EqualsVerifier cannot instantiate by itself. * - * @param The class of the prefabricated values. + * @param The class of the prefabricated values. * @param fieldName The name of the field that the prefabricated values are linked to. - * @param red An instance of {@code S}. - * @param blue Another instance of {@code S}, not equal to {@code red}. + * @param red An instance of {@code S}. + * @param blue Another instance of {@code S}, not equal to {@code red}. * @return {@code this}, for easy method chaining. - * @throws NullPointerException If {@code red} or {@code blue} is null, or if the named field - * does not exist in the class. + * @throws NullPointerException If {@code red} or {@code blue} is null, or if the named field does not exist in + * the class. * @throws IllegalArgumentException If {@code red} equals {@code blue}. */ - public SingleTypeEqualsVerifierApi withPrefabValuesForField( - String fieldName, - S red, - S blue - ) { + public SingleTypeEqualsVerifierApi withPrefabValuesForField(String fieldName, S red, S blue) { PrefabValuesApi.addPrefabValuesForField(fieldCache, objenesis, type, fieldName, red, blue); withNonnullFields(fieldName); return this; @@ -151,20 +137,14 @@ public SingleTypeEqualsVerifierApi withPrefabValuesForField( /** {@inheritDoc} */ @Override - public SingleTypeEqualsVerifierApi withGenericPrefabValues( - Class otherType, - Func1 factory - ) { + public SingleTypeEqualsVerifierApi withGenericPrefabValues(Class otherType, Func1 factory) { PrefabValuesApi.addGenericPrefabValues(factoryCache, otherType, factory); return this; } /** {@inheritDoc} */ @Override - public SingleTypeEqualsVerifierApi withGenericPrefabValues( - Class otherType, - Func2 factory - ) { + public SingleTypeEqualsVerifierApi withGenericPrefabValues(Class otherType, Func2 factory) { PrefabValuesApi.addGenericPrefabValues(factoryCache, otherType, factory); return this; } @@ -178,9 +158,7 @@ public SingleTypeEqualsVerifierApi usingGetClass() { /** {@inheritDoc} */ @Override - public SingleTypeEqualsVerifierApi withFieldnameToGetterConverter( - Function converter - ) { + public SingleTypeEqualsVerifierApi withFieldnameToGetterConverter(Function converter) { this.fieldnameToGetter = converter; return this; } @@ -190,7 +168,8 @@ public SingleTypeEqualsVerifierApi withFieldnameToGetterConverter( * EqualsVerifier} will not fail if one of these fields does not affect the outcome of {@code * equals}, but it will fail if one of these fields does affect the outcome of {@code equals}. * - *

Note that these fields will still be used to test for null-ness, among other things. + *

+ * Note that these fields will still be used to test for null-ness, among other things. * * @param fields Fields that should be ignored. * @return {@code this}, for easy method chaining. @@ -200,10 +179,9 @@ public SingleTypeEqualsVerifierApi withIgnoredFields(String... fields) { } /** - * Signals that all given fields, and only the given fields, are relevant for the - * {@code equals} contract. {@code EqualsVerifier} will fail if one of these fields does not - * affect the outcome of {@code equals}, and it will fail if a field that isn't listed here, - * does affect the outcome of {@code equals}. + * Signals that all given fields, and only the given fields, are relevant for the {@code equals} contract. + * {@code EqualsVerifier} will fail if one of these fields does not affect the outcome of {@code equals}, and it + * will fail if a field that isn't listed here, does affect the outcome of {@code equals}. * * @param fields Fields that should be ignored. * @return {@code this}, for easy method chaining. @@ -213,27 +191,23 @@ public SingleTypeEqualsVerifierApi withOnlyTheseFields(String... fields) { } private SingleTypeEqualsVerifierApi withFieldsAddedAndValidated( - Set collection, - List specifiedFields - ) { + Set collection, + List specifiedFields) { collection.addAll(specifiedFields); Validations.validateFields(allIncludedFields, allExcludedFields); Validations.validateFieldNamesExist(type, specifiedFields, actualFields); - Validations.validateWarningsAndFields( - warningsToSuppress, - allIncludedFields, - allExcludedFields - ); + Validations.validateWarningsAndFields(warningsToSuppress, allIncludedFields, allExcludedFields); return this; } /** - * Signals that all given fields can never be null, and {@code EqualsVerifier} therefore doesn't - * have to verify that proper null checks are in place for these fields. + * Signals that all given fields can never be null, and {@code EqualsVerifier} therefore doesn't have to verify that + * proper null checks are in place for these fields. * - *

This can be used instead of {link #suppress(Warning...)}, which provides the same - * behaviour for all fields, when only some fields are never null but others are. + *

+ * This can be used instead of {link #suppress(Warning...)}, which provides the same behaviour for all fields, when + * only some fields are never null but others are. * * @param fields Fields that can never be null. * @return {@code this}, for easy method chaining. @@ -249,8 +223,9 @@ public SingleTypeEqualsVerifierApi withNonnullFields(String... fields) { /** * Signals that all given annotations are to be ignored by EqualsVerifier. * - *

For instance, EqualsVerifier normally doesn't perform null verifications on fields marked - * with an {@code @Nonnull} annotation. However, if this method is called with a {@code + *

+ * For instance, EqualsVerifier normally doesn't perform null verifications on fields marked with an + * {@code @Nonnull} annotation. However, if this method is called with a {@code * Nonnull.class} parameter, the null verifications will be performed after all. * * @param annotations Annotations to ignore. @@ -265,12 +240,11 @@ public SingleTypeEqualsVerifierApi withIgnoredAnnotations(Class... annotat } /** - * Signals that T is part of an inheritance hierarchy where {@code equals} is overridden. Call - * this method if T has overridden {@code equals} and {@code hashCode}, and one or more of T's - * superclasses have as well. + * Signals that T is part of an inheritance hierarchy where {@code equals} is overridden. Call this method if T has + * overridden {@code equals} and {@code hashCode}, and one or more of T's superclasses have as well. * - *

T itself does not necessarily have to have subclasses that redefine {@code equals} and - * {@code hashCode}. + *

+ * T itself does not necessarily have to have subclasses that redefine {@code equals} and {@code hashCode}. * * @return {@code this}, for easy method chaining. */ @@ -280,11 +254,12 @@ public SingleTypeEqualsVerifierApi withRedefinedSuperclass() { } /** - * Supplies a reference to a subclass of T in which {@code equals} is overridden. Calling this - * method is mandatory if {@code equals} is not final and a strong verification is performed. + * Supplies a reference to a subclass of T in which {@code equals} is overridden. Calling this method is mandatory + * if {@code equals} is not final and a strong verification is performed. * - *

Note that, for each subclass that overrides {@code equals}, {@link EqualsVerifier} should - * be used as well to verify its adherence to the contracts. + *

+ * Note that, for each subclass that overrides {@code equals}, {@link EqualsVerifier} should be used as well to + * verify its adherence to the contracts. * * @param subclass A subclass of T for which no instance can be equal to any instance of T. * @return {@code this}, for easy method chaining. @@ -299,48 +274,43 @@ public SingleTypeEqualsVerifierApi withRedefinedSubclass(Class s * Signals that T caches its hashCode, instead of re-calculating it each time the {@code * hashCode()} method is called. * - *

There are 3 conditions to verify cached hashCodes: + *

+ * There are 3 conditions to verify cached hashCodes: * - *

First, the class under test must have a private int field that contains the cached - * hashCode. + *

+ * First, the class under test must have a private int field that contains the cached hashCode. * - *

Second, the class under test must have a private method that calculates the hashCode. The - * method must return an int and may not take any parameters. It should be used by the - * constructor or the hashCode method of the class under test to initialize the cached hashCode. - * This may lead to slightly awkward production code, but unfortunately, it is necessary for - * EqualsVerifier to verify that the hashCode is correct. + *

+ * Second, the class under test must have a private method that calculates the hashCode. The method must return an + * int and may not take any parameters. It should be used by the constructor or the hashCode method of the class + * under test to initialize the cached hashCode. This may lead to slightly awkward production code, but + * unfortunately, it is necessary for EqualsVerifier to verify that the hashCode is correct. * - *

Finally, only immutable objects can be verified. In other words, {@code + *

+ * Finally, only immutable objects can be verified. In other words, {@code * withCachedHashCode} can not be used when {@link Warning#NONFINAL_FIELDS} is suppressed. * - * @param cachedHashCodeField The name of the field which stores the cached hash code. - * @param calculateHashCodeMethod The name of the method which recomputes the hash code. It - * should return an int and take no parameters. - * @param example An instance of the class under test, to verify that the hashCode has been - * initialized properly. + * @param cachedHashCodeField The name of the field which stores the cached hash code. + * @param calculateHashCodeMethod The name of the method which recomputes the hash code. It should return an int and + * take no parameters. + * @param example An instance of the class under test, to verify that the hashCode has been + * initialized properly. * @return {@code this}, for easy method chaining. */ public SingleTypeEqualsVerifierApi withCachedHashCode( - String cachedHashCodeField, - String calculateHashCodeMethod, - T example - ) { + String cachedHashCodeField, + String calculateHashCodeMethod, + T example) { cachedHashCodeInitializer = - new CachedHashCodeInitializer<>( - type, - cachedHashCodeField, - calculateHashCodeMethod, - example - ); + new CachedHashCodeInitializer<>(type, cachedHashCodeField, calculateHashCodeMethod, example); return this; } /** - * Signals that T uses Lombok to cache its hashCode, instead of re-calculating it each time the - * {@code hashCode()} method is called. + * Signals that T uses Lombok to cache its hashCode, instead of re-calculating it each time the {@code hashCode()} + * method is called. * - * @param example An instance of the class under test, to verify that the hashCode has been - * initialized properly. + * @param example An instance of the class under test, to verify that the hashCode has been initialized properly. * @return {@code this}, for easy method chaining. * @see #withCachedHashCode(String, String, Object) */ @@ -351,6 +321,7 @@ public SingleTypeEqualsVerifierApi withLombokCachedHashCode(T example) { /** * {@inheritDoc} + * * @deprecated No longer needed; this happens automatically. */ @Deprecated @@ -360,65 +331,59 @@ public SingleTypeEqualsVerifierApi withResetCaches() { } /** - * Performs the verification of the contracts for {@code equals} and {@code hashCode} and throws - * an {@link AssertionError} if there is a problem. + * Performs the verification of the contracts for {@code equals} and {@code hashCode} and throws an + * {@link AssertionError} if there is a problem. * - * @throws AssertionError If the contract is not met, or if {@link EqualsVerifier}'s - * preconditions do not hold. + * @throws AssertionError If the contract is not met, or if {@link EqualsVerifier}'s preconditions do not hold. */ public void verify() { try { performVerification(); - } catch (MessagingException e) { + } + catch (MessagingException e) { throw new AssertionError(buildErrorMessage(e.getDescription(), true), e); - } catch (Throwable e) { + } + catch (Throwable e) { throw new AssertionError(buildErrorMessage(e.getMessage(), true), e); } } /** - * Performs the verification of the contracts for {@code equals} and {@code hashCode} and - * returns an {@link EqualsVerifierReport} with the results of the verification. + * Performs the verification of the contracts for {@code equals} and {@code hashCode} and returns an + * {@link EqualsVerifierReport} with the results of the verification. * - * @return An {@link EqualsVerifierReport} that indicates whether the contract is met and - * whether {@link EqualsVerifier}'s preconditions hold. + * @return An {@link EqualsVerifierReport} that indicates whether the contract is met and whether + * {@link EqualsVerifier}'s preconditions hold. */ public EqualsVerifierReport report() { return report(true); } /** - * Performs the verification of the contracts for {@code equals} and {@code hashCode} and - * returns an {@link EqualsVerifierReport} with the results of the verification. + * Performs the verification of the contracts for {@code equals} and {@code hashCode} and returns an + * {@link EqualsVerifierReport} with the results of the verification. * * @param showUrl Whether or not to show the url at the end of the error message. - * @return An {@link EqualsVerifierReport} that indicates whether the contract is met and - * whether {@link EqualsVerifier}'s preconditions hold. + * @return An {@link EqualsVerifierReport} that indicates whether the contract is met and whether + * {@link EqualsVerifier}'s preconditions hold. */ public EqualsVerifierReport report(boolean showUrl) { try { performVerification(); return EqualsVerifierReport.success(type); - } catch (MessagingException e) { - return EqualsVerifierReport.failure( - type, - buildErrorMessage(e.getDescription(), showUrl), - e - ); - } catch (Throwable e) { - return EqualsVerifierReport.failure( - type, - buildErrorMessage(e.getMessage(), showUrl), - e - ); + } + catch (MessagingException e) { + return EqualsVerifierReport.failure(type, buildErrorMessage(e.getDescription(), showUrl), e); + } + catch (Throwable e) { + return EqualsVerifierReport.failure(type, buildErrorMessage(e.getMessage(), showUrl), e); } } private String buildErrorMessage(String description, boolean showUrl) { String message = description == null ? "" : description; - String result = Formatter - .of("EqualsVerifier found a problem in class %%.\n-> %%", type.getName(), message) - .format(); + String result = + Formatter.of("EqualsVerifier found a problem in class %%.\n-> %%", type.getName(), message).format(); if (showUrl) { result += "\n\n" + ErrorMessage.suffix(); } @@ -433,47 +398,42 @@ private void performVerification() { Configuration config = buildConfig(); Context context = new Context<>(config, factoryCache, fieldCache, objenesis); - Validations.validateProcessedAnnotations( - type, - config.getAnnotationCache(), - warningsToSuppress, - allIncludedFields, - allExcludedFields - ); + Validations + .validateProcessedAnnotations( + type, + config.getAnnotationCache(), + warningsToSuppress, + allIncludedFields, + allExcludedFields); verifyWithoutExamples(context); verifyWithExamples(context); } private Configuration buildConfig() { - return Configuration.build( - type, - allExcludedFields, - allIncludedFields, - nonnullFields, - fieldCache.getFieldNames(), - cachedHashCodeInitializer, - hasRedefinedSuperclass, - redefinedSubclass, - usingGetClass, - warningsToSuppress, - fieldnameToGetter, - ignoredAnnotationClassNames, - actualFields, - equalExamples, - unequalExamples - ); + return Configuration + .build( + type, + allExcludedFields, + allIncludedFields, + nonnullFields, + fieldCache.getFieldNames(), + cachedHashCodeInitializer, + hasRedefinedSuperclass, + redefinedSubclass, + usingGetClass, + warningsToSuppress, + fieldnameToGetter, + ignoredAnnotationClassNames, + actualFields, + equalExamples, + unequalExamples); } private void verifyWithoutExamples(Context context) { Configuration config = context.getConfiguration(); - Checker[] checkers = { - new SignatureChecker<>(context), - new AbstractDelegationChecker<>(context), - new NullChecker<>(context), - new RecordChecker<>(context), - new CachedHashCodeChecker<>(config) - }; + Checker[] checkers = { new SignatureChecker<>(context), new AbstractDelegationChecker<>(context), + new NullChecker<>(context), new RecordChecker<>(context), new CachedHashCodeChecker<>(config) }; for (Checker checker : checkers) { checker.check(); @@ -481,12 +441,8 @@ private void verifyWithoutExamples(Context context) { } private void verifyWithExamples(Context context) { - Checker[] checkers = { - new ExamplesChecker<>(context), - new HierarchyChecker<>(context), - new FieldsChecker<>(context), - new MapEntryHashCodeRequirementChecker<>(context) - }; + Checker[] checkers = { new ExamplesChecker<>(context), new HierarchyChecker<>(context), + new FieldsChecker<>(context), new MapEntryHashCodeRequirementChecker<>(context) }; for (Checker checker : checkers) { checker.check(); diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/SuppressFBWarnings.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/SuppressFBWarnings.java index 2750319d7..55f7c88de 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/SuppressFBWarnings.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/SuppressFBWarnings.java @@ -6,7 +6,8 @@ // CHECKSTYLE OFF: AbbreviationAsWordInName /** - * Copied over from spotbugs-annotations to avoid the dependency; see https://github.com/jqno/equalsverifier/issues/1026. + * Copied over from spotbugs-annotations to avoid the dependency; see + * https://github.com/jqno/equalsverifier/issues/1026. */ @Retention(RetentionPolicy.CLASS) public @interface SuppressFBWarnings { diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/AbstractDelegationChecker.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/AbstractDelegationChecker.java index 63b3cb93c..71b403652 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/AbstractDelegationChecker.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/AbstractDelegationChecker.java @@ -3,6 +3,7 @@ import static nl.jqno.equalsverifier.internal.util.Assert.fail; import java.lang.reflect.Field; + import nl.jqno.equalsverifier.internal.SuppressFBWarnings; import nl.jqno.equalsverifier.internal.instantiation.SubjectCreator; import nl.jqno.equalsverifier.internal.instantiation.ValueProvider; @@ -45,14 +46,15 @@ private void checkAbstractEqualsAndHashCode() { if (equalsIsAbstract && hashCodeIsAbstract) { fail( - Formatter.of( - "Abstract delegation: %%'s equals and hashCode methods are both abstract. They should be concrete.", - type.getSimpleName() - ) - ); - } else if (equalsIsAbstract) { + Formatter + .of( + "Abstract delegation: %%'s equals and hashCode methods are both abstract. They should be concrete.", + type.getSimpleName())); + } + else if (equalsIsAbstract) { fail(buildSingleAbstractMethodErrorMessage(type, true, true)); - } else if (hashCodeIsAbstract) { + } + else if (hashCodeIsAbstract) { fail(buildSingleAbstractMethodErrorMessage(type, false, true)); } } @@ -72,7 +74,8 @@ private void checkAbstractDelegationInFields() { private Tuple safelyGetTuple(TypeTag tag) { try { return valueProvider.provideOrThrow(tag); - } catch (Exception ignored) { + } + catch (Exception ignored) { // If it fails for some reason, any reason, just return null so we can skip the test. return null; } @@ -83,76 +86,61 @@ private void checkAbstractDelegation(T instance, T copy) { } private Formatter buildSingleAbstractMethodErrorMessage( - Class c, - boolean isEqualsAbstract, - boolean bothShouldBeConcrete - ) { - return Formatter.of( - "Abstract delegation: %%'s %% method is abstract, but %% is not.\n%%", - c.getSimpleName(), - isEqualsAbstract ? "equals" : "hashCode", - isEqualsAbstract ? "hashCode" : "equals", - bothShouldBeConcrete - ? "Both should be concrete." - : "Both should be either abstract or concrete." - ); + Class c, + boolean isEqualsAbstract, + boolean bothShouldBeConcrete) { + return Formatter + .of( + "Abstract delegation: %%'s %% method is abstract, but %% is not.\n%%", + c.getSimpleName(), + isEqualsAbstract ? "equals" : "hashCode", + isEqualsAbstract ? "hashCode" : "equals", + bothShouldBeConcrete ? "Both should be concrete." : "Both should be either abstract or concrete."); } @SuppressFBWarnings( - value = "DE_MIGHT_IGNORE", - justification = "These exceptions will re-occur and be handled later." - ) - private void checkAbstractMethods( - Class instanceClass, - S instance, - S copy, - boolean prefabPossible - ) { + value = "DE_MIGHT_IGNORE", + justification = "These exceptions will re-occur and be handled later.") + private void checkAbstractMethods(Class instanceClass, S instance, S copy, boolean prefabPossible) { try { instance.equals(copy); - } catch (AbstractMethodError e) { - Formatter f = buildAbstractDelegationErrorMessage( - instanceClass, - prefabPossible, - "equals", - e.getMessage() - ); + } + catch (AbstractMethodError e) { + Formatter f = buildAbstractDelegationErrorMessage(instanceClass, prefabPossible, "equals", e.getMessage()); fail(f, e); - } catch (Exception ignored) { + } + catch (Exception ignored) { // Skip. We only care about AbstractMethodError at this point; // other errors will be handled later. } try { cachedHashCodeInitializer.getInitializedHashCode(instance); - } catch (AbstractMethodError e) { - Formatter f = buildAbstractDelegationErrorMessage( - instanceClass, - prefabPossible, - "hashCode", - e.getMessage() - ); + } + catch (AbstractMethodError e) { + Formatter f = + buildAbstractDelegationErrorMessage(instanceClass, prefabPossible, "hashCode", e.getMessage()); fail(f, e); - } catch (Exception ignored) { + } + catch (Exception ignored) { // Skip. We only care about AbstractMethodError at this point; // other errors will be handled later. } } private Formatter buildAbstractDelegationErrorMessage( - Class c, - boolean prefabPossible, - String method, - String originalMessage - ) { + Class c, + boolean prefabPossible, + String method, + String originalMessage) { Formatter prefabFormatter = Formatter.of("\nAdd prefab values for %%.", c.getName()); - return Formatter.of( - "Abstract delegation: %%'s %% method delegates to an abstract method:\n %%%%", - c.getSimpleName(), - method, - originalMessage, - prefabPossible ? prefabFormatter.format() : "" - ); + return Formatter + .of( + "Abstract delegation: %%'s %% method delegates to an abstract method:\n %%%%", + c.getSimpleName(), + method, + originalMessage, + prefabPossible ? prefabFormatter.format() : ""); } } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/CachedHashCodeChecker.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/CachedHashCodeChecker.java index 318e65274..069e480b8 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/CachedHashCodeChecker.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/CachedHashCodeChecker.java @@ -3,6 +3,7 @@ import static nl.jqno.equalsverifier.internal.util.Assert.*; import java.util.EnumSet; + import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.util.CachedHashCodeInitializer; import nl.jqno.equalsverifier.internal.util.Configuration; @@ -25,23 +26,20 @@ public void check() { } if (warningsToSuppress.contains(Warning.NONFINAL_FIELDS)) { fail( - Formatter.of( - "Cached hashCode: EqualsVerifier can only check cached hashCodes for immutable classes." - ) - ); + Formatter.of("Cached hashCode: EqualsVerifier can only check cached hashCodes for immutable classes.")); } T reference = cachedHashCodeInitializer.getExample(); if (warningsToSuppress.contains(Warning.NO_EXAMPLE_FOR_CACHED_HASHCODE)) { if (reference != null) { fail( - Formatter.of( - "Cached hashCode: example must be null if %% is suppressed", - Warning.NO_EXAMPLE_FOR_CACHED_HASHCODE.name() - ) - ); + Formatter + .of( + "Cached hashCode: example must be null if %% is suppressed", + Warning.NO_EXAMPLE_FOR_CACHED_HASHCODE.name())); } - } else { + } + else { if (reference == null) { fail(Formatter.of("Cached hashCode: example cannot be null.")); } @@ -51,14 +49,10 @@ public void check() { assertEquals( Formatter.of("Cached hashCode: hashCode is not properly initialized."), actualHashCode, - recomputedHashCode - ); + recomputedHashCode); assertFalse( - Formatter.of( - "Cached hashCode: example.hashCode() cannot be zero. Please choose a different example." - ), - actualHashCode == 0 - ); + Formatter.of("Cached hashCode: example.hashCode() cannot be zero. Please choose a different example."), + actualHashCode == 0); } } } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/ExamplesChecker.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/ExamplesChecker.java index ba1e91f9f..49821959b 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/ExamplesChecker.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/ExamplesChecker.java @@ -7,6 +7,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Objects; + import nl.jqno.equalsverifier.internal.SuppressFBWarnings; import nl.jqno.equalsverifier.internal.exceptions.AssertionException; import nl.jqno.equalsverifier.internal.instantiation.SubjectCreator; @@ -65,33 +66,19 @@ private List ensureEnoughExamples(List examples) { private void checkPreconditions() { for (T example : equalExamples) { assertTrue( - Formatter.of( - "Precondition:\n %%\nand\n %%\nare of different classes", - equalExamples.get(0), - example - ), - type.isAssignableFrom(example.getClass()) - ); + Formatter.of("Precondition:\n %%\nand\n %%\nare of different classes", equalExamples.get(0), example), + type.isAssignableFrom(example.getClass())); } } private void checkEqualButNotIdentical(T reference, T other) { - assertFalse( - Formatter.of("Precondition: the same object appears twice:\n %%", reference), - reference == other - ); + assertFalse(Formatter.of("Precondition: the same object appears twice:\n %%", reference), reference == other); assertFalse( Formatter.of("Precondition: two identical objects appear:\n %%", reference), - isIdentical(reference, other) - ); + isIdentical(reference, other)); assertTrue( - Formatter.of( - "Precondition: not all equal objects are equal:\n %%\nand\n %%", - reference, - other - ), - reference.equals(other) - ); + Formatter.of("Precondition: not all equal objects are equal:\n %%\nand\n %%", reference, other), + reference.equals(other)); } private void checkSingle(T reference) { @@ -108,26 +95,26 @@ private void checkReflexivity(T reference) { assertEquals( Formatter.of("Reflexivity: object does not equal itself:\n %%", reference), reference, - reference - ); - } catch (ClassCastException e) { - Formatter f = Formatter.of( - "Generics: ClassCastException was thrown. Consider using" + - " withGenericPrefabValues for the type that triggered the exception." - ); + reference); + } + catch (ClassCastException e) { + Formatter f = Formatter + .of( + "Generics: ClassCastException was thrown. Consider using" + + " withGenericPrefabValues for the type that triggered the exception."); fail(f, e); } } @SuppressFBWarnings( - value = { "EC_NULL_ARG", "DCN_NULLPOINTER_EXCEPTION" }, - justification = "Check what happens when null is passed into equals." - ) + value = { "EC_NULL_ARG", "DCN_NULLPOINTER_EXCEPTION" }, + justification = "Check what happens when null is passed into equals.") private void checkNonNullity(T reference) { try { boolean nullity = reference.equals(null); assertFalse(Formatter.of("Non-nullity: true returned for null value"), nullity); - } catch (NullPointerException e) { + } + catch (NullPointerException e) { fail(Formatter.of("Non-nullity: NullPointerException thrown"), e); } } @@ -135,24 +122,25 @@ private void checkNonNullity(T reference) { private void checkTypeCheck(T reference) { SomethingElse somethingElse = new SomethingElse(); try { - Formatter f = Formatter.of( - "Type-check: equals returns true for an unrelated type.\n" + - "Add an instanceof or getClass() check." - ); + Formatter f = Formatter + .of( + "Type-check: equals returns true for an unrelated type.\n" + + "Add an instanceof or getClass() check."); assertFalse(f, reference.equals(somethingElse)); - } catch (AssertionException e) { + } + catch (AssertionException e) { throw e; - } catch (ClassCastException e) { - Formatter f = Formatter.of( - "Type-check: equals throws ClassCastException.\n" + - "Add an instanceof or getClass() check." - ); + } + catch (ClassCastException e) { + Formatter f = Formatter + .of("Type-check: equals throws ClassCastException.\nAdd an instanceof or getClass() check."); fail(f, e); - } catch (Exception e) { - Formatter f = Formatter.of( - "Type-check: equals throws %%.\nAdd an instanceof or getClass() check.", - e.getClass().getSimpleName() - ); + } + catch (Exception e) { + Formatter f = Formatter + .of( + "Type-check: equals throws %%.\nAdd an instanceof or getClass() check.", + e.getClass().getSimpleName()); fail(f, e); } } @@ -160,27 +148,22 @@ private void checkTypeCheck(T reference) { private void checkHashCode(T reference, T copy) { int referenceHashCode = cachedHashCodeInitializer.getInitializedHashCode(reference); assertEquals( - Formatter.of( - "hashCode: hashCode should be consistent:\n %% (%%)", - reference, - referenceHashCode - ), + Formatter.of("hashCode: hashCode should be consistent:\n %% (%%)", reference, referenceHashCode), referenceHashCode, - cachedHashCodeInitializer.getInitializedHashCode(reference) - ); + cachedHashCodeInitializer.getInitializedHashCode(reference)); if (!reference.equals(copy)) { return; } int copyHashCode = cachedHashCodeInitializer.getInitializedHashCode(copy); - Formatter f = Formatter.of( - "hashCode: hashCodes should be equal:\n %% (%%)\nand\n %% (%%)", - reference, - referenceHashCode, - copy, - copyHashCode - ); + Formatter f = Formatter + .of( + "hashCode: hashCodes should be equal:\n %% (%%)\nand\n %% (%%)", + reference, + referenceHashCode, + copy, + copyHashCode); assertEquals(f, referenceHashCode, copyHashCode); } @@ -198,9 +181,8 @@ private boolean isIdentical(T reference, T other) { } @SuppressFBWarnings( - value = "HE_HASHCODE_USE_OBJECT_EQUALS", - justification = "The hashCode must be stable, the class has no state so we don't need to override equals" - ) + value = "HE_HASHCODE_USE_OBJECT_EQUALS", + justification = "The hashCode must be stable, the class has no state so we don't need to override equals") private static final class SomethingElse { @Override diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/FieldInspector.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/FieldInspector.java index 9905082c6..75f2ac147 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/FieldInspector.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/FieldInspector.java @@ -1,6 +1,7 @@ package nl.jqno.equalsverifier.internal.checkers; import java.lang.reflect.Field; + import nl.jqno.equalsverifier.internal.checkers.fieldchecks.FieldCheck; import nl.jqno.equalsverifier.internal.reflection.FieldIterable; import nl.jqno.equalsverifier.internal.reflection.FieldProbe; diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/FieldsChecker.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/FieldsChecker.java index 2aab34ba8..4199ecfd2 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/FieldsChecker.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/FieldsChecker.java @@ -1,6 +1,7 @@ package nl.jqno.equalsverifier.internal.checkers; import java.util.function.Predicate; + import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.checkers.fieldchecks.*; import nl.jqno.equalsverifier.internal.instantiation.SubjectCreator; @@ -34,31 +35,21 @@ public FieldsChecker(Context context) { final TypeTag typeTag = config.getTypeTag(); final SubjectCreator subjectCreator = context.getSubjectCreator(); - final String cachedHashCodeFieldName = config - .getCachedHashCodeInitializer() - .getCachedHashCodeFieldName(); - final Predicate isCachedHashCodeField = p -> - p.getName().equals(cachedHashCodeFieldName); + final String cachedHashCodeFieldName = config.getCachedHashCodeInitializer().getCachedHashCodeFieldName(); + final Predicate isCachedHashCodeField = p -> p.getName().equals(cachedHashCodeFieldName); - this.arrayFieldCheck = - new ArrayFieldCheck<>(subjectCreator, config.getCachedHashCodeInitializer()); + this.arrayFieldCheck = new ArrayFieldCheck<>(subjectCreator, config.getCachedHashCodeInitializer()); this.floatAndDoubleFieldCheck = new FloatAndDoubleFieldCheck<>(subjectCreator); - this.mutableStateFieldCheck = - new MutableStateFieldCheck<>(subjectCreator, isCachedHashCodeField); + this.mutableStateFieldCheck = new MutableStateFieldCheck<>(subjectCreator, isCachedHashCodeField); this.reflexivityFieldCheck = new ReflexivityFieldCheck<>(context); this.significantFieldCheck = new SignificantFieldCheck<>(context, isCachedHashCodeField); this.symmetryFieldCheck = new SymmetryFieldCheck<>(subjectCreator); - this.transientFieldsCheck = - new TransientFieldsCheck<>(subjectCreator, typeTag, config.getAnnotationCache()); + this.transientFieldsCheck = new TransientFieldsCheck<>(subjectCreator, typeTag, config.getAnnotationCache()); this.transitivityFieldCheck = new TransitivityFieldCheck<>(subjectCreator); - this.stringFieldCheck = - new StringFieldCheck<>( - subjectCreator, + this.stringFieldCheck = new StringFieldCheck<>(subjectCreator, context.getValueProvider(), - config.getCachedHashCodeInitializer() - ); - this.bigDecimalFieldCheck = - new BigDecimalFieldCheck<>(subjectCreator, config.getCachedHashCodeInitializer()); + config.getCachedHashCodeInitializer()); + this.bigDecimalFieldCheck = new BigDecimalFieldCheck<>(subjectCreator, config.getCachedHashCodeInitializer()); this.jpaLazyGetterFieldCheck = new JpaLazyGetterFieldCheck<>(context); } @@ -90,20 +81,16 @@ public void check() { } AnnotationCache cache = config.getAnnotationCache(); - if ( - cache.hasClassAnnotation(config.getType(), SupportedAnnotations.ENTITY) && - !config.getWarningsToSuppress().contains(Warning.JPA_GETTER) - ) { + if (cache.hasClassAnnotation(config.getType(), SupportedAnnotations.ENTITY) + && !config.getWarningsToSuppress().contains(Warning.JPA_GETTER)) { inspector.check(jpaLazyGetterFieldCheck); } } private boolean ignoreMutability(Class type) { AnnotationCache cache = config.getAnnotationCache(); - return ( - config.getWarningsToSuppress().contains(Warning.NONFINAL_FIELDS) || - cache.hasClassAnnotation(type, SupportedAnnotations.IMMUTABLE) || - cache.hasClassAnnotation(type, SupportedAnnotations.ENTITY) - ); + return config.getWarningsToSuppress().contains(Warning.NONFINAL_FIELDS) + || cache.hasClassAnnotation(type, SupportedAnnotations.IMMUTABLE) + || cache.hasClassAnnotation(type, SupportedAnnotations.ENTITY); } } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/HierarchyChecker.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/HierarchyChecker.java index 1367ef57f..f2c161b0f 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/HierarchyChecker.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/HierarchyChecker.java @@ -5,6 +5,7 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; + import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.SuppressFBWarnings; import nl.jqno.equalsverifier.internal.instantiation.SubjectCreator; @@ -29,15 +30,10 @@ public class HierarchyChecker implements Checker { public HierarchyChecker(Context context) { this.config = context.getConfiguration(); - this.strictnessSuppressed = - config.getWarningsToSuppress().contains(Warning.STRICT_INHERITANCE); + this.strictnessSuppressed = config.getWarningsToSuppress().contains(Warning.STRICT_INHERITANCE); this.hasRedefinedSubclass = config.getRedefinedSubclass() != null; if (strictnessSuppressed && hasRedefinedSubclass) { - fail( - Formatter.of( - "withRedefinedSubclass and weakInheritanceCheck are mutually exclusive." - ) - ); + fail(Formatter.of("withRedefinedSubclass and weakInheritanceCheck are mutually exclusive.")); } this.type = context.getType(); @@ -68,38 +64,31 @@ private void checkSuperclass() { T reference = subjectCreator.plain(); Object equalSuper = getEqualSuper(reference); - Formatter formatter = Formatter.of( - "Redefined superclass:\n" + - " %%\nshould not equal superclass instance\n %%\nbut it does.", - reference, - equalSuper - ); + Formatter formatter = Formatter + .of( + "Redefined superclass:\n %%\nshould not equal superclass instance\n %%\nbut it does.", + reference, + equalSuper); try { - assertFalse( - formatter, - reference.equals(equalSuper) || equalSuper.equals(reference) - ); - } catch (AbstractMethodError ignored) { + assertFalse(formatter, reference.equals(equalSuper) || equalSuper.equals(reference)); + } + catch (AbstractMethodError ignored) { // In this case, we'll assume all super properties hold. // The problems we test for, can never occur anyway if you can't instantiate a super // instance. } - } else { - safelyCheckSuperProperties( - subjectCreator.plain(), - subjectCreator.withAllFieldsShallowlyChanged() - ); + } + else { + safelyCheckSuperProperties(subjectCreator.plain(), subjectCreator.withAllFieldsShallowlyChanged()); safelyCheckSuperProperties( subjectCreator.withAllFieldsDefaulted(), - subjectCreator.withAllFieldsShallowlyChanged() - ); + subjectCreator.withAllFieldsShallowlyChanged()); } } @SuppressFBWarnings( - value = "DCN_NULLPOINTER_EXCEPTION", - justification = "The equals method in a superclasses can throw an NPE, but it's a specific non-goal to do something with that here." - ) + value = "DCN_NULLPOINTER_EXCEPTION", + justification = "The equals method in a superclasses can throw an NPE, but it's a specific non-goal to do something with that here.") private void safelyCheckSuperProperties(T reference, T shallowScrambled) { if (strictnessSuppressed) { return; @@ -109,7 +98,8 @@ private void safelyCheckSuperProperties(T reference, T shallowScrambled) { try { checkSuperProperties(reference, equalSuper, shallowScrambled); - } catch (AbstractMethodError | NullPointerException ignored) { + } + catch (AbstractMethodError | NullPointerException ignored) { // In these cases, we'll assume all super properties hold. // The problems we test for, can never occur anyway if you can't instantiate a super // instance. @@ -117,34 +107,30 @@ private void safelyCheckSuperProperties(T reference, T shallowScrambled) { } private void checkSuperProperties(T reference, Object equalSuper, T shallow) { - Formatter symmetryFormatter = Formatter.of( - "Symmetry:\n %%\ndoes not equal superclass instance\n %%", - reference, - equalSuper - ); + Formatter symmetryFormatter = + Formatter.of("Symmetry:\n %%\ndoes not equal superclass instance\n %%", reference, equalSuper); assertTrue(symmetryFormatter, reference.equals(equalSuper) && equalSuper.equals(reference)); - Formatter transitivityFormatter = Formatter.of( - "Transitivity:\n" + - " %%\nand\n %%\nboth equal superclass instance\n %%\nwhich implies they equal each other.", - reference, - shallow, - equalSuper - ); + Formatter transitivityFormatter = Formatter + .of( + "Transitivity:\n" + + " %%\nand\n %%\nboth equal superclass instance\n %%\nwhich implies they equal each other.", + reference, + shallow, + equalSuper); assertTrue( transitivityFormatter, - reference.equals(shallow) || reference.equals(equalSuper) != equalSuper.equals(shallow) - ); + reference.equals(shallow) || reference.equals(equalSuper) != equalSuper.equals(shallow)); int referenceHashCode = cachedHashCodeInitializer.getInitializedHashCode(reference); int equalSuperHashCode = cachedHashCodeInitializer.getInitializedHashCode(equalSuper); - Formatter superclassFormatter = Formatter.of( - "Superclass: hashCode for\n %% (%%)\nshould be equal to hashCode for superclass instance\n %% (%%)", - reference, - referenceHashCode, - equalSuper, - equalSuperHashCode - ); + Formatter superclassFormatter = Formatter + .of( + "Superclass: hashCode for\n %% (%%)\nshould be equal to hashCode for superclass instance\n %% (%%)", + reference, + referenceHashCode, + equalSuper, + equalSuperHashCode); assertTrue(superclassFormatter, referenceHashCode == equalSuperHashCode); } @@ -160,26 +146,27 @@ private void checkSubclass() { T reference = subjectCreator.plain(); @SuppressWarnings("unchecked") - Class anonymousSubclass = (Class) Instantiator.giveDynamicSubclass( - reference.getClass() // don't use type directly, as reference may already be a subclass if type was abstract - ); + // don't use type directly, as reference may already be a subclass if type was abstract + Class realClass = (Class) reference.getClass(); + Class anonymousSubclass = Instantiator.giveDynamicSubclass(realClass); T equalSub = subjectCreator.copyIntoSubclass(reference, anonymousSubclass); if (config.isUsingGetClass()) { - Formatter formatter = Formatter.of( - "Subclass: object is equal to an instance of a trivial subclass with" + - " equal fields:\n %%\nThis should not happen when using getClass().", - reference - ); + Formatter formatter = Formatter + .of( + "Subclass: object is equal to an instance of a trivial subclass with" + + " equal fields:\n %%\nThis should not happen when using getClass().", + reference); assertFalse(formatter, reference.equals(equalSub)); - } else { - Formatter formatter = Formatter.of( - "Subclass: object is not equal to an instance of a trivial subclass" + - " with equal fields:\n %%\n" + - "Maybe you forgot to add usingGetClass(). Otherwise, consider" + - " making the class final or use EqualsVerifier.simple().", - reference - ); + } + else { + Formatter formatter = Formatter + .of( + "Subclass: object is not equal to an instance of a trivial subclass" + + " with equal fields:\n %%\n" + + "Maybe you forgot to add usingGetClass(). Otherwise, consider" + + " making the class final or use EqualsVerifier.simple().", + reference); assertTrue(formatter, reference.equals(equalSub)); } } @@ -191,29 +178,21 @@ private void checkRedefinedSubclass() { if (methodIsFinal("equals", Object.class)) { fail( - Formatter.of( - "Subclass: %% has a final equals method.\nNo need to supply a redefined subclass.", - type.getSimpleName() - ) - ); + Formatter + .of( + "Subclass: %% has a final equals method.\nNo need to supply a redefined subclass.", + type.getSimpleName())); } T reference = subjectCreator.plain(); T redefinedSub = subjectCreator.copyIntoSubclass(reference, redefinedSubclass); assertFalse( - Formatter.of( - "Subclass:\n %%\nequals subclass instance\n %%", - reference, - redefinedSub - ), - reference.equals(redefinedSub) - ); + Formatter.of("Subclass:\n %%\nequals subclass instance\n %%", reference, redefinedSub), + reference.equals(redefinedSub)); } private void checkFinalEqualsMethod() { - boolean isEntity = config - .getAnnotationCache() - .hasClassAnnotation(type, SupportedAnnotations.ENTITY); + boolean isEntity = config.getAnnotationCache().hasClassAnnotation(type, SupportedAnnotations.ENTITY); if (strictnessSuppressed || isEntity || typeIsFinal || hasRedefinedSubclass) { return; } @@ -223,27 +202,24 @@ private void checkFinalEqualsMethod() { if (config.isUsingGetClass()) { assertEquals( - Formatter.of( - "Finality: equals and hashCode must both be final or both be non-final." - ), + Formatter.of("Finality: equals and hashCode must both be final or both be non-final."), equalsIsFinal, - hashCodeIsFinal - ); - } else { - Formatter equalsFormatter = Formatter.of( - "Subclass: equals is not final.\n" + - "Make your class or your equals method final, or supply an" + - " instance of a redefined subclass using withRedefinedSubclass" + - " if equals cannot be final." - ); + hashCodeIsFinal); + } + else { + Formatter equalsFormatter = Formatter + .of( + "Subclass: equals is not final.\nMake your class or your equals method final, or supply an" + + " instance of a redefined subclass using withRedefinedSubclass" + + " if equals cannot be final."); assertTrue(equalsFormatter, equalsIsFinal); - Formatter hashCodeFormatter = Formatter.of( - "Subclass: hashCode is not final.\n" + - "Make your class or your hashCode method final, or supply an" + - " instance of a redefined subclass using withRedefinedSubclass" + - " if hashCode cannot be final." - ); + Formatter hashCodeFormatter = Formatter + .of( + "Subclass: hashCode is not final.\n" + + "Make your class or your hashCode method final, or supply an" + + " instance of a redefined subclass using withRedefinedSubclass" + + " if hashCode cannot be final."); assertTrue(hashCodeFormatter, hashCodeIsFinal); } } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/MapEntryHashCodeRequirementChecker.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/MapEntryHashCodeRequirementChecker.java index 7e219f02f..9a52da73b 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/MapEntryHashCodeRequirementChecker.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/MapEntryHashCodeRequirementChecker.java @@ -4,6 +4,7 @@ import java.util.Map; import java.util.Objects; + import nl.jqno.equalsverifier.internal.instantiation.ValueProvider; import nl.jqno.equalsverifier.internal.util.Configuration; import nl.jqno.equalsverifier.internal.util.Context; @@ -22,23 +23,21 @@ public MapEntryHashCodeRequirementChecker(Context context) { @Override public void check() { if (Map.Entry.class.isAssignableFrom(config.getType())) { - Map.Entry e = valueProvider - .>provideOrThrow(config.getTypeTag()) - .getRed(); + Map.Entry e = valueProvider.>provideOrThrow(config.getTypeTag()).getRed(); int expectedHashCode = Objects.hashCode(e.getKey()) ^ Objects.hashCode(e.getValue()); int actualHashCode = config.getCachedHashCodeInitializer().getInitializedHashCode(e); - Formatter f = Formatter.of( - "Map.Entry: hashCode for\n %%\nshould be %% but was %%.\n" + - "The hash code of a map entry e is defined as:\n" + - " (e.getKey()==null ? 0 : e.getKey().hashCode()) ^ (e.getValue()==null ? 0 : e.getValue().hashCode())\n" + - "or, using Java 8 API:\n" + - " java.util.Objects.hashCode(e.getKey()) ^ java.util.Objects.hashCode(e.getValue())", - e, - expectedHashCode, - actualHashCode - ); + Formatter f = Formatter + .of( + "Map.Entry: hashCode for\n %%\nshould be %% but was %%.\n" + + "The hash code of a map entry e is defined as:\n" + + " (e.getKey()==null ? 0 : e.getKey().hashCode()) ^ (e.getValue()==null ? 0 : e.getValue().hashCode())\n" + + "or, using Java 8 API:\n" + + " java.util.Objects.hashCode(e.getKey()) ^ java.util.Objects.hashCode(e.getValue())", + e, + expectedHashCode, + actualHashCode); assertEquals(f, expectedHashCode, actualHashCode); } } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/RecordChecker.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/RecordChecker.java index 1ac829845..b803473b1 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/RecordChecker.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/RecordChecker.java @@ -9,6 +9,7 @@ import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; + import nl.jqno.equalsverifier.internal.instantiation.SubjectCreator; import nl.jqno.equalsverifier.internal.reflection.ClassProbe; import nl.jqno.equalsverifier.internal.reflection.FieldIterable; @@ -53,18 +54,18 @@ private void verifyRecordPrecondition(T original) { if (!originalField.equals(copyField)) { failedFields.add(f.getName()); } - } catch (IllegalAccessException | InvocationTargetException e) { + } + catch (IllegalAccessException | InvocationTargetException e) { fail(Formatter.of("Record: failed to run accessor method: " + accessorMethod)); } } fail( - Formatter.of( - "Record invariant: constructor invariant failed for field%%: %%", - failedFields.size() > 1 ? "s" : "", - failedFields.stream().collect(Collectors.joining(",")) - ) - ); + Formatter + .of( + "Record invariant: constructor invariant failed for field%%: %%", + failedFields.size() > 1 ? "s" : "", + failedFields.stream().collect(Collectors.joining(",")))); } private Method getAccessorMethodFor(Class type, Field f) { diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/SignatureChecker.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/SignatureChecker.java index 15ae77d89..d48142105 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/SignatureChecker.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/SignatureChecker.java @@ -7,6 +7,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Set; + import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.reflection.ClassProbe; import nl.jqno.equalsverifier.internal.util.Context; @@ -49,12 +50,7 @@ private List getEqualsMethods() { } private void failOverloaded(String message) { - fail( - Formatter.of( - "Overloaded: %%.\nSignature should be: public boolean equals(Object obj)", - message - ) - ); + fail(Formatter.of("Overloaded: %%.\nSignature should be: public boolean equals(Object obj)", message)); } private void checkEquals(Method equals) { @@ -75,19 +71,14 @@ private void checkEquals(Method equals) { } private void checkEqualsIsDefined() { - boolean dontAllowDirectlyInherited = !warningsToSuppress.contains( - Warning.INHERITED_DIRECTLY_FROM_OBJECT - ); + boolean dontAllowDirectlyInherited = !warningsToSuppress.contains(Warning.INHERITED_DIRECTLY_FROM_OBJECT); boolean isDirectlyInherited = classProbe.isEqualsInheritedFromObject(); if (dontAllowDirectlyInherited && isDirectlyInherited) { fail( - Formatter.of( - "Equals is inherited directly from Object.\n" + - "Suppress Warning." + - Warning.INHERITED_DIRECTLY_FROM_OBJECT.name() + - " to skip this check." - ) - ); + Formatter + .of( + "Equals is inherited directly from Object.\nSuppress Warning." + + Warning.INHERITED_DIRECTLY_FROM_OBJECT.name() + " to skip this check.")); } } } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/ArrayFieldCheck.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/ArrayFieldCheck.java index c269b96d8..539432d20 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/ArrayFieldCheck.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/ArrayFieldCheck.java @@ -3,6 +3,7 @@ import static nl.jqno.equalsverifier.internal.util.Assert.assertEquals; import java.lang.reflect.Array; + import nl.jqno.equalsverifier.internal.instantiation.SubjectCreator; import nl.jqno.equalsverifier.internal.reflection.FieldProbe; import nl.jqno.equalsverifier.internal.util.CachedHashCodeInitializer; @@ -13,10 +14,7 @@ public class ArrayFieldCheck implements FieldCheck { private final SubjectCreator subjectCreator; private final CachedHashCodeInitializer cachedHashCodeInitializer; - public ArrayFieldCheck( - SubjectCreator subjectCreator, - CachedHashCodeInitializer cachedHashCodeInitializer - ) { + public ArrayFieldCheck(SubjectCreator subjectCreator, CachedHashCodeInitializer cachedHashCodeInitializer) { this.subjectCreator = subjectCreator; this.cachedHashCodeInitializer = cachedHashCodeInitializer; } @@ -36,7 +34,8 @@ public void execute(FieldProbe fieldProbe) { if (arrayType.getComponentType().isArray()) { assertDeep(fieldProbe.getName(), reference, changed); - } else { + } + else { assertArray(fieldProbe.getName(), reference, changed); } } @@ -56,7 +55,8 @@ private Object arrayCopy(Object array) { for (int i = 0; i < length; i++) { if (componentType.isArray()) { Array.set(result, i, arrayCopy(Array.get(array, i))); - } else { + } + else { Array.set(result, i, Array.get(array, i)); } } @@ -64,41 +64,32 @@ private Object arrayCopy(Object array) { } private void assertDeep(String fieldName, Object reference, Object changed) { - Formatter eqEqFormatter = Formatter.of( - "Multidimensional array: ==, regular equals() or Arrays.equals() used" + - " instead of Arrays.deepEquals() for field %%.", - fieldName - ); + Formatter eqEqFormatter = Formatter + .of( + "Multidimensional array: ==, regular equals() or Arrays.equals() used" + + " instead of Arrays.deepEquals() for field %%.", + fieldName); assertEquals(eqEqFormatter, reference, changed); - Formatter regularFormatter = Formatter.of( - "Multidimensional array: regular hashCode() or Arrays.hashCode() used" + - " instead of Arrays.deepHashCode() for field %%.", - fieldName - ); + Formatter regularFormatter = Formatter + .of( + "Multidimensional array: regular hashCode() or Arrays.hashCode() used" + + " instead of Arrays.deepHashCode() for field %%.", + fieldName); assertEquals( regularFormatter, cachedHashCodeInitializer.getInitializedHashCode(reference), - cachedHashCodeInitializer.getInitializedHashCode(changed) - ); + cachedHashCodeInitializer.getInitializedHashCode(changed)); } private void assertArray(String fieldName, Object reference, Object changed) { assertEquals( - Formatter.of( - "Array: == or regular equals() used instead of Arrays.equals() for field %%.", - fieldName - ), + Formatter.of("Array: == or regular equals() used instead of Arrays.equals() for field %%.", fieldName), reference, - changed - ); + changed); assertEquals( - Formatter.of( - "Array: regular hashCode() used instead of Arrays.hashCode() for field %%.", - fieldName - ), + Formatter.of("Array: regular hashCode() used instead of Arrays.hashCode() for field %%.", fieldName), cachedHashCodeInitializer.getInitializedHashCode(reference), - cachedHashCodeInitializer.getInitializedHashCode(changed) - ); + cachedHashCodeInitializer.getInitializedHashCode(changed)); } } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/BigDecimalFieldCheck.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/BigDecimalFieldCheck.java index 9ec15ae89..5fbebeea2 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/BigDecimalFieldCheck.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/BigDecimalFieldCheck.java @@ -5,6 +5,7 @@ import java.lang.reflect.Field; import java.math.BigDecimal; import java.math.RoundingMode; + import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.instantiation.SubjectCreator; import nl.jqno.equalsverifier.internal.reflection.FieldProbe; @@ -19,9 +20,8 @@ public class BigDecimalFieldCheck implements FieldCheck { private final CachedHashCodeInitializer cachedHashCodeInitializer; public BigDecimalFieldCheck( - SubjectCreator subjectCreator, - CachedHashCodeInitializer cachedHashCodeInitializer - ) { + SubjectCreator subjectCreator, + CachedHashCodeInitializer cachedHashCodeInitializer) { this.subjectCreator = subjectCreator; this.cachedHashCodeInitializer = cachedHashCodeInitializer; } @@ -32,10 +32,7 @@ public void execute(FieldProbe fieldProbe) { T left = subjectCreator.plain(); BigDecimal referenceValue = (BigDecimal) fieldProbe.getValue(left); - BigDecimal changedValue = referenceValue.setScale( - referenceValue.scale() + 1, - RoundingMode.UNNECESSARY - ); + BigDecimal changedValue = referenceValue.setScale(referenceValue.scale() + 1, RoundingMode.UNNECESSARY); T right = subjectCreator.withFieldSetTo(fieldProbe.getField(), changedValue); @@ -44,45 +41,31 @@ public void execute(FieldProbe fieldProbe) { } } - private void checkEquals( - Field field, - BigDecimal referenceValue, - BigDecimal changedValue, - T left, - T right - ) { - Formatter f = Formatter.of( - ERROR_DOC_TITLE + - ": object does not equal a copy of itself" + - " where BigDecimal field %% has a value that is equal using compareTo: %% compared to %%" + - "\nIf these values should be considered equal then use compareTo rather than equals for this field." + - "\nIf these values should not be considered equal, suppress Warning.%% to disable this check.", - field.getName(), - referenceValue, - changedValue, - Warning.BIGDECIMAL_EQUALITY - ); + private void checkEquals(Field field, BigDecimal referenceValue, BigDecimal changedValue, T left, T right) { + Formatter f = Formatter + .of( + ERROR_DOC_TITLE + ": object does not equal a copy of itself" + + " where BigDecimal field %% has a value that is equal using compareTo: %% compared to %%" + + "\nIf these values should be considered equal then use compareTo rather than equals for this field." + + "\nIf these values should not be considered equal, suppress Warning.%% to disable this check.", + field.getName(), + referenceValue, + changedValue, + Warning.BIGDECIMAL_EQUALITY); assertEquals(f, left, right); } - private void checkHashCode( - Field field, - BigDecimal referenceValue, - BigDecimal changedValue, - T left, - T right - ) { - Formatter f = Formatter.of( - ERROR_DOC_TITLE + - ": hashCode of object does not equal hashCode of a copy of itself" + - " where BigDecimal field %% has a value that is equal using compareTo: %% compared to %%" + - "\nIf these values should be considered equal then make sure to derive the same constituent hashCode from this field." + - "\nIf these values should not be considered equal, suppress Warning.%% to disable this check.", - field.getName(), - referenceValue, - changedValue, - Warning.BIGDECIMAL_EQUALITY - ); + private void checkHashCode(Field field, BigDecimal referenceValue, BigDecimal changedValue, T left, T right) { + Formatter f = Formatter + .of( + ERROR_DOC_TITLE + ": hashCode of object does not equal hashCode of a copy of itself" + + " where BigDecimal field %% has a value that is equal using compareTo: %% compared to %%" + + "\nIf these values should be considered equal then make sure to derive the same constituent hashCode from this field." + + "\nIf these values should not be considered equal, suppress Warning.%% to disable this check.", + field.getName(), + referenceValue, + changedValue, + Warning.BIGDECIMAL_EQUALITY); int leftHashCode = cachedHashCodeInitializer.getInitializedHashCode(left); int rightHashCode = cachedHashCodeInitializer.getInitializedHashCode(right); assertEquals(f, leftHashCode, rightHashCode); diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/FloatAndDoubleFieldCheck.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/FloatAndDoubleFieldCheck.java index a970b2e3f..805b52164 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/FloatAndDoubleFieldCheck.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/FloatAndDoubleFieldCheck.java @@ -21,25 +21,17 @@ public void execute(FieldProbe fieldProbe) { T reference = subjectCreator.withFieldSetTo(fieldProbe.getField(), Float.NaN); T copy = subjectCreator.withFieldSetTo(fieldProbe.getField(), Float.NaN); assertEquals( - Formatter.of( - "Float: equals doesn't use Float.compare for field %%.", - fieldProbe.getName() - ), + Formatter.of("Float: equals doesn't use Float.compare for field %%.", fieldProbe.getName()), reference, - copy - ); + copy); } if (isDouble(type)) { T reference = subjectCreator.withFieldSetTo(fieldProbe.getField(), Double.NaN); T copy = subjectCreator.withFieldSetTo(fieldProbe.getField(), Double.NaN); assertEquals( - Formatter.of( - "Double: equals doesn't use Double.compare for field %%.", - fieldProbe.getName() - ), + Formatter.of("Double: equals doesn't use Double.compare for field %%.", fieldProbe.getName()), reference, - copy - ); + copy); } } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/JpaLazyGetterFieldCheck.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/JpaLazyGetterFieldCheck.java index 1ed068764..fe29fa0eb 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/JpaLazyGetterFieldCheck.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/JpaLazyGetterFieldCheck.java @@ -7,6 +7,7 @@ import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.function.Function; + import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.exceptions.EqualsVerifierInternalBugException; import nl.jqno.equalsverifier.internal.instantiation.SubjectCreator; @@ -45,23 +46,20 @@ public void execute(FieldProbe fieldProbe) { String fieldName = fieldProbe.getName(); String getterName = fieldnameToGetter.apply(fieldName); - if ( - !fieldIsUsed(fieldProbe.getField(), true) || - !fieldIsLazy(fieldName) || - Modifier.isFinal(type.getModifiers()) - ) { + if (!fieldIsUsed(fieldProbe.getField(), true) + || !fieldIsLazy(fieldName) + || Modifier.isFinal(type.getModifiers())) { return; } assertTrue( - Formatter.of( - "Class %% doesn't contain getter %%() for field %%.", - classProbe.getType().getSimpleName(), - getterName, - fieldName - ), - classProbe.hasMethod(getterName) - ); + Formatter + .of( + "Class %% doesn't contain getter %%() for field %%.", + classProbe.getType().getSimpleName(), + getterName, + fieldName), + classProbe.hasMethod(getterName)); TypeTag sub = new TypeTag(throwingGetterCreator(getterName)); Tuple tuple = valueProvider.provideOrThrow(sub); @@ -71,7 +69,8 @@ public void execute(FieldProbe fieldProbe) { boolean equalsExceptionCaught = false; try { red1.equals(red2); - } catch (EqualsVerifierInternalBugException e) { + } + catch (EqualsVerifierInternalBugException e) { equalsExceptionCaught = true; } assertEntity(fieldName, "equals", getterName, equalsExceptionCaught); @@ -80,7 +79,8 @@ public void execute(FieldProbe fieldProbe) { boolean hashCodeExceptionCaught = false; try { red1.hashCode(); - } catch (EqualsVerifierInternalBugException e) { + } + catch (EqualsVerifierInternalBugException e) { hashCodeExceptionCaught = true; } assertEntity(fieldName, "hashCode", getterName, hashCodeExceptionCaught || !usedInHashcode); @@ -92,47 +92,35 @@ private boolean fieldIsUsed(Field field, boolean forEquals) { if (forEquals) { return !red.equals(blue); - } else { + } + else { return red.hashCode() != blue.hashCode(); } } private boolean fieldIsLazy(String fieldName) { - return ( - annotationCache.hasFieldAnnotation( - type, - fieldName, - SupportedAnnotations.JPA_LINKED_FIELD - ) || - annotationCache.hasFieldAnnotation(type, fieldName, SupportedAnnotations.JPA_LAZY_FIELD) - ); + return annotationCache.hasFieldAnnotation(type, fieldName, SupportedAnnotations.JPA_LINKED_FIELD) + || annotationCache.hasFieldAnnotation(type, fieldName, SupportedAnnotations.JPA_LAZY_FIELD); } private Class throwingGetterCreator(String getterName) { - return Instantiator.giveDynamicSubclass( - type, - getterName, - builder -> - builder - .method(named(getterName)) - .intercept(throwing(EqualsVerifierInternalBugException.class)) - ); + return Instantiator + .giveDynamicSubclass( + type, + getterName, + builder -> builder + .method(named(getterName)) + .intercept(throwing(EqualsVerifierInternalBugException.class))); } - private void assertEntity( - String fieldName, - String method, - String getterName, - boolean assertion - ) { + private void assertEntity(String fieldName, String method, String getterName, boolean assertion) { assertTrue( - Formatter.of( - "JPA Entity: direct reference to field %% used in %% instead of getter %%().", - fieldName, - method, - getterName - ), - assertion - ); + Formatter + .of( + "JPA Entity: direct reference to field %% used in %% instead of getter %%().", + fieldName, + method, + getterName), + assertion); } } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/MutableStateFieldCheck.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/MutableStateFieldCheck.java index 9d71e65ee..0c0415061 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/MutableStateFieldCheck.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/MutableStateFieldCheck.java @@ -3,6 +3,7 @@ import static nl.jqno.equalsverifier.internal.util.Assert.fail; import java.util.function.Predicate; + import nl.jqno.equalsverifier.internal.instantiation.SubjectCreator; import nl.jqno.equalsverifier.internal.reflection.FieldProbe; import nl.jqno.equalsverifier.internal.util.Formatter; @@ -12,10 +13,7 @@ public class MutableStateFieldCheck implements FieldCheck { private final SubjectCreator subjectCreator; private final Predicate isCachedHashCodeField; - public MutableStateFieldCheck( - SubjectCreator subjectCreator, - Predicate isCachedHashCodeField - ) { + public MutableStateFieldCheck(SubjectCreator subjectCreator, Predicate isCachedHashCodeField) { this.subjectCreator = subjectCreator; this.isCachedHashCodeField = isCachedHashCodeField; } @@ -34,10 +32,8 @@ public void execute(FieldProbe fieldProbe) { boolean equalAfter = reference.equals(changed); if (equalBefore && !equalAfter && !fieldProbe.isFinal()) { - String message = - "Mutability: equals depends on mutable field %%.\n" + - "Make the field final, suppress Warning.NONFINAL_FIELDS or use" + - " EqualsVerifier.simple()"; + String message = "Mutability: equals depends on mutable field %%.\n" + + "Make the field final, suppress Warning.NONFINAL_FIELDS or use EqualsVerifier.simple()"; fail(Formatter.of(message, fieldProbe.getName())); } } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/NullPointerExceptionFieldCheck.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/NullPointerExceptionFieldCheck.java index 7219616f7..9291b92e3 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/NullPointerExceptionFieldCheck.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/NullPointerExceptionFieldCheck.java @@ -3,16 +3,14 @@ import static nl.jqno.equalsverifier.internal.util.Assert.fail; import java.lang.reflect.Field; + import nl.jqno.equalsverifier.internal.SuppressFBWarnings; import nl.jqno.equalsverifier.internal.instantiation.SubjectCreator; import nl.jqno.equalsverifier.internal.reflection.FieldMutator; import nl.jqno.equalsverifier.internal.reflection.FieldProbe; import nl.jqno.equalsverifier.internal.util.*; -@SuppressFBWarnings( - value = "RV_RETURN_VALUE_IGNORED", - justification = "We only want to see if it throws an exception." -) +@SuppressFBWarnings(value = "RV_RETURN_VALUE_IGNORED", justification = "We only want to see if it throws an exception.") public class NullPointerExceptionFieldCheck implements FieldCheck { private final Configuration config; @@ -40,13 +38,11 @@ public void execute(FieldProbe fieldProbe) { FieldMutator fieldMutator = new FieldMutator(fieldProbe); Object saved = fieldProbe.getValue(reference); - fieldMutator.setNewValue( - reference, - PrimitiveMappers.DEFAULT_VALUE_MAPPER.get(fieldProbe.getType()) - ); + fieldMutator.setNewValue(reference, PrimitiveMappers.DEFAULT_VALUE_MAPPER.get(fieldProbe.getType())); performTests(fieldProbe.getField(), subjectCreator.plain(), subjectCreator.plain()); fieldMutator.setNewValue(reference, saved); - } else { + } + else { T changed = subjectCreator.withFieldDefaulted(fieldProbe.getField()); performTests(fieldProbe.getField(), subjectCreator.plain(), changed); } @@ -55,67 +51,57 @@ public void execute(FieldProbe fieldProbe) { private void performTests(Field field, final Object reference, final Object changed) { handle("equals", "the parameter's field", field, () -> reference.equals(changed)); handle("equals", "the 'this' object's field", field, () -> changed.equals(reference)); - handle( - "hashCode", - "field", - field, - () -> config.getCachedHashCodeInitializer().getInitializedHashCode(changed) - ); + handle("hashCode", "field", field, () -> config.getCachedHashCodeInitializer().getInitializedHashCode(changed)); } @SuppressFBWarnings( - value = "DCN_NULLPOINTER_EXCEPTION", - justification = "We're catching and wrapping it to provide better output to the user." - ) + value = "DCN_NULLPOINTER_EXCEPTION", + justification = "We're catching and wrapping it to provide better output to the user.") private void handle(String testedMethodName, String whichOne, Field field, Runnable r) { try { r.run(); - } catch (NullPointerException e) { + } + catch (NullPointerException e) { npeThrown(testedMethodName, whichOne, field, e); - } catch (AbstractMethodError e) { + } + catch (AbstractMethodError e) { abstractMethodErrorThrown(testedMethodName, field, e); - } catch (ClassCastException e) { + } + catch (ClassCastException e) { classCastExceptionThrown(field, e); - } catch (Exception e) { + } + catch (Exception e) { exceptionThrown(testedMethodName, field, e); } } private void npeThrown(String method, String whichOne, Field field, NullPointerException e) { - Formatter f = Formatter.of( - "Non-nullity: %% throws NullPointerException on %% %%.", - method, - whichOne, - field.getName() - ); + Formatter f = Formatter + .of("Non-nullity: %% throws NullPointerException on %% %%.", method, whichOne, field.getName()); fail(f, e); } private void abstractMethodErrorThrown(String method, Field field, AbstractMethodError e) { - Formatter f = Formatter.of( - "Abstract delegation: %% throws AbstractMethodError when field %% is null.\n" + - "Suppress Warning.NULL_FIELDS to disable this check.", - method, - field.getName() - ); + Formatter f = Formatter + .of( + "Abstract delegation: %% throws AbstractMethodError when field %% is null.\n" + + "Suppress Warning.NULL_FIELDS to disable this check.", + method, + field.getName()); fail(f, e); } private void classCastExceptionThrown(Field field, ClassCastException e) { - Formatter f = Formatter.of( - "Generics: ClassCastException was thrown. Consider using withGenericPrefabValues for %%.", - field.getType().getSimpleName() - ); + Formatter f = Formatter + .of( + "Generics: ClassCastException was thrown. Consider using withGenericPrefabValues for %%.", + field.getType().getSimpleName()); fail(f, e); } private void exceptionThrown(String method, Field field, Exception e) { - Formatter f = Formatter.of( - "%% throws %% when field %% is null.", - method, - e.getClass().getSimpleName(), - field.getName() - ); + Formatter f = Formatter + .of("%% throws %% when field %% is null.", method, e.getClass().getSimpleName(), field.getName()); fail(f, e); } } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/ReflexivityFieldCheck.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/ReflexivityFieldCheck.java index 9e28dea88..0c5752e01 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/ReflexivityFieldCheck.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/ReflexivityFieldCheck.java @@ -6,6 +6,7 @@ import java.lang.reflect.Field; import java.util.EnumSet; import java.util.Set; + import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.instantiation.SubjectCreator; import nl.jqno.equalsverifier.internal.instantiation.ValueProvider; @@ -80,19 +81,18 @@ private void checkValueReflexivity(FieldProbe probe) { Field field = probe.getField(); String fieldName = field.getName(); TypeTag tag = TypeTag.of(field, typeTag); - Tuple tuple = prefabbedFields.contains(fieldName) - ? fieldCache.get(fieldName) - : valueProvider.provideOrThrow(tag); + Tuple tuple = + prefabbedFields.contains(fieldName) ? fieldCache.get(fieldName) : valueProvider.provideOrThrow(tag); Object left = subjectCreator.withFieldSetTo(field, tuple.getRed()); Object right = subjectCreator.withFieldSetTo(field, tuple.getRedCopy()); - Formatter f = Formatter.of( - "Reflexivity: == used instead of .equals() on field: %%" + - "\nIf this is intentional, consider suppressing Warning.%%", - probe.getName(), - Warning.REFERENCE_EQUALITY.toString() - ); + Formatter f = Formatter + .of( + "Reflexivity: == used instead of .equals() on field: %%" + + "\nIf this is intentional, consider suppressing Warning.%%", + probe.getName(), + Warning.REFERENCE_EQUALITY.toString()); assertEquals(f, left, right); } @@ -116,31 +116,30 @@ private void checkNullReflexivity(FieldProbe fieldProbe) { private void checkReflexivityFor(T left, T right) { if (warningsToSuppress.contains(Warning.IDENTICAL_COPY)) { - Formatter f = Formatter.of( - "Unnecessary suppression: %%. Two identical copies are equal.", - Warning.IDENTICAL_COPY.toString() - ); + Formatter f = Formatter + .of( + "Unnecessary suppression: %%. Two identical copies are equal.", + Warning.IDENTICAL_COPY.toString()); assertFalse(f, left.equals(right)); - } else { - boolean isEntity = annotationCache.hasClassAnnotation( - typeTag.getType(), - SupportedAnnotations.ENTITY - ); + } + else { + boolean isEntity = annotationCache.hasClassAnnotation(typeTag.getType(), SupportedAnnotations.ENTITY); if (isEntity) { - Formatter f = Formatter.of( - "Reflexivity: entity does not equal an identical copy of itself:\n %%" + - "\nIf this is intentional, consider suppressing Warning.%%.", - left, - Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY.toString() - ); + Formatter f = Formatter + .of( + "Reflexivity: entity does not equal an identical copy of itself:\n %%" + + "\nIf this is intentional, consider suppressing Warning.%%.", + left, + Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY.toString()); assertEquals(f, left, right); - } else { - Formatter f = Formatter.of( - "Reflexivity: object does not equal an identical copy of itself:\n %%" + - "\nIf this is intentional, consider suppressing Warning.%%.", - left, - Warning.IDENTICAL_COPY.toString() - ); + } + else { + Formatter f = Formatter + .of( + "Reflexivity: object does not equal an identical copy of itself:\n %%" + + "\nIf this is intentional, consider suppressing Warning.%%.", + left, + Warning.IDENTICAL_COPY.toString()); assertEquals(f, left, right); } } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/SignificantFieldCheck.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/SignificantFieldCheck.java index 19d530ea8..77dc6fcc1 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/SignificantFieldCheck.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/SignificantFieldCheck.java @@ -6,6 +6,7 @@ import java.util.EnumSet; import java.util.Set; import java.util.function.Predicate; + import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.instantiation.SubjectCreator; import nl.jqno.equalsverifier.internal.reflection.FieldProbe; @@ -46,33 +47,24 @@ public void execute(FieldProbe fieldProbe) { subjectCreator.plain(), subjectCreator.withFieldChanged(fieldProbe.getField()), fieldProbe, - false - ); + false); if (fieldProbe.canBeDefault(config)) { checkValues( subjectCreator.withAllFieldsDefaulted(), subjectCreator.withAllFieldsDefaulted(), subjectCreator.withAllFieldsDefaultedExcept(fieldProbe.getField()), fieldProbe, - true - ); + true); } } - private void checkValues( - T reference, - T copy, - T changed, - FieldProbe probe, - boolean testWithNull - ) { + private void checkValues(T reference, T copy, T changed, FieldProbe probe, boolean testWithNull) { String fieldName = probe.getField().getName(); boolean equalToItself = reference.equals(copy); boolean equalsChanged = !reference.equals(changed); - boolean hashCodeChanged = - cachedHashCodeInitializer.getInitializedHashCode(reference) != - cachedHashCodeInitializer.getInitializedHashCode(changed); + boolean hashCodeChanged = cachedHashCodeInitializer + .getInitializedHashCode(reference) != cachedHashCodeInitializer.getInitializedHashCode(changed); assertEqualsAndHashCodeRelyOnSameFields( equalsChanged, @@ -80,88 +72,69 @@ private void checkValues( reference, changed, fieldName, - testWithNull - ); - assertFieldShouldBeIgnored( - equalToItself, - equalsChanged, - reference, - probe, - fieldName, - testWithNull - ); + testWithNull); + assertFieldShouldBeIgnored(equalToItself, equalsChanged, reference, probe, fieldName, testWithNull); } private void assertEqualsAndHashCodeRelyOnSameFields( - boolean equalsChanged, - boolean hashCodeChanged, - T reference, - T changed, - String fieldName, - boolean testWithNull - ) { + boolean equalsChanged, + boolean hashCodeChanged, + T reference, + T changed, + String fieldName, + boolean testWithNull) { if (equalsChanged != hashCodeChanged) { boolean skipEqualsHasMoreThanHashCodeTest = - warningsToSuppress.contains(Warning.STRICT_HASHCODE) || testWithNull; + warningsToSuppress.contains(Warning.STRICT_HASHCODE) || testWithNull; if (!skipEqualsHasMoreThanHashCodeTest) { - Formatter formatter = Formatter.of( - "Significant fields: equals relies on %%, but hashCode does not." + - "\n %% has hashCode %%\n %% has hashCode %%", - fieldName, - reference, - reference.hashCode(), - changed, - changed.hashCode() - ); + Formatter formatter = Formatter + .of( + "Significant fields: equals relies on %%, but hashCode does not." + + "\n %% has hashCode %%\n %% has hashCode %%", + fieldName, + reference, + reference.hashCode(), + changed, + changed.hashCode()); assertFalse(formatter, equalsChanged); } - Formatter formatter = Formatter.of( - "Significant fields: hashCode relies on %%, but equals does not.\n" + - "These objects are equal, but probably shouldn't be:\n %%\nand\n %%", - fieldName, - reference, - changed - ); + Formatter formatter = Formatter + .of( + "Significant fields: hashCode relies on %%, but equals does not.\n" + + "These objects are equal, but probably shouldn't be:\n %%\nand\n %%", + fieldName, + reference, + changed); assertFalse(formatter, hashCodeChanged); } } private void assertFieldShouldBeIgnored( - boolean equalToItself, - boolean equalsChanged, - T object, - FieldProbe fieldProbe, - String fieldName, - boolean testWithNull - ) { + boolean equalToItself, + boolean equalsChanged, + T object, + FieldProbe fieldProbe, + String fieldName, + boolean testWithNull) { if (!shouldAllFieldsBeUsed(fieldProbe) || !isFieldEligible(fieldProbe)) { return; } boolean fieldShouldBeIgnored = ignoredFields.contains(fieldName); - boolean thisFieldIsMarkedAsId = annotationCache.hasFieldAnnotation( - type, - fieldName, - SupportedAnnotations.ID - ); + boolean thisFieldIsMarkedAsId = annotationCache.hasFieldAnnotation(type, fieldName, SupportedAnnotations.ID); boolean anotherFieldIsMarkedAsId = - !thisFieldIsMarkedAsId && - annotationCache.hasClassAnnotation(type, SupportedAnnotations.ID); + !thisFieldIsMarkedAsId && annotationCache.hasClassAnnotation(type, SupportedAnnotations.ID); if (!fieldIsEmptyAndItsOk(thisFieldIsMarkedAsId, fieldProbe, object)) { if (!fieldShouldBeIgnored) { - assertTrue( - Formatter.of("Significant fields: equals does not use %%.", fieldName), - equalToItself - ); + assertTrue(Formatter.of("Significant fields: equals does not use %%.", fieldName), equalToItself); } assertFieldShouldHaveBeenUsed( fieldName, equalsChanged, fieldShouldBeIgnored, thisFieldIsMarkedAsId, - anotherFieldIsMarkedAsId - ); + anotherFieldIsMarkedAsId); } assertFieldShouldNotBeUsed( fieldName, @@ -169,66 +142,49 @@ private void assertFieldShouldBeIgnored( fieldShouldBeIgnored, thisFieldIsMarkedAsId, anotherFieldIsMarkedAsId, - testWithNull - ); + testWithNull); } private boolean shouldAllFieldsBeUsed(FieldProbe fieldProbe) { - return ( - !warningsToSuppress.contains(Warning.ALL_FIELDS_SHOULD_BE_USED) && - !(warningsToSuppress.contains(Warning.ALL_NONFINAL_FIELDS_SHOULD_BE_USED) && - !fieldProbe.isFinal()) - ); + return !warningsToSuppress.contains(Warning.ALL_FIELDS_SHOULD_BE_USED) + && !(warningsToSuppress.contains(Warning.ALL_NONFINAL_FIELDS_SHOULD_BE_USED) && !fieldProbe.isFinal()); } private boolean isFieldEligible(FieldProbe fieldProbe) { - return ( - !fieldProbe.isStatic() && - !fieldProbe.isTransient() && - !fieldProbe.isEmptyOrSingleValueEnum() && - !annotationCache.hasFieldAnnotation( - type, - fieldProbe.getField().getName(), - SupportedAnnotations.TRANSIENT - ) - ); + return !fieldProbe.isStatic() + && !fieldProbe.isTransient() + && !fieldProbe.isEmptyOrSingleValueEnum() + && !annotationCache + .hasFieldAnnotation(type, fieldProbe.getField().getName(), SupportedAnnotations.TRANSIENT); } - private boolean fieldIsEmptyAndItsOk( - boolean thisFieldIsMarkedAsId, - FieldProbe fieldProbe, - T object - ) { + private boolean fieldIsEmptyAndItsOk(boolean thisFieldIsMarkedAsId, FieldProbe fieldProbe, T object) { Object value = fieldProbe.getValue(object); Class fieldType = fieldProbe.getType(); Object zero = PrimitiveMappers.DEFAULT_WRAPPED_VALUE_MAPPER.get(fieldType); boolean fieldIsEmpty = value == null || value.equals(zero); - return ( - thisFieldIsMarkedAsId && - warningsToSuppress.contains(Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY) && - fieldIsEmpty - ); + return thisFieldIsMarkedAsId + && warningsToSuppress.contains(Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY) + && fieldIsEmpty; } private void assertFieldShouldHaveBeenUsed( - String fieldName, - boolean equalsChanged, - boolean fieldShouldBeIgnored, - boolean thisFieldIsMarkedAsId, - boolean anotherFieldIsMarkedAsId - ) { + String fieldName, + boolean equalsChanged, + boolean fieldShouldBeIgnored, + boolean thisFieldIsMarkedAsId, + boolean anotherFieldIsMarkedAsId) { final String message; if (thisFieldIsMarkedAsId) { - message = - "Significant fields: %% is marked @Id or @EmbeddedId and Warning.SURROGATE_KEY" + - " is suppressed, but equals does not use it."; - } else if (anotherFieldIsMarkedAsId) { - message = - "Significant fields: equals does not use %%, or it is stateless.\n" + - "Suppress Warning.SURROGATE_KEY if you want to use only the @Id or" + - " @EmbeddedId field(s)."; - } else { + message = "Significant fields: %% is marked @Id or @EmbeddedId and Warning.SURROGATE_KEY" + + " is suppressed, but equals does not use it."; + } + else if (anotherFieldIsMarkedAsId) { + message = "Significant fields: equals does not use %%, or it is stateless.\n" + + "Suppress Warning.SURROGATE_KEY if you want to use only the @Id or @EmbeddedId field(s)."; + } + else { message = "Significant fields: equals does not use %%, or it is stateless."; } @@ -236,31 +192,26 @@ private void assertFieldShouldHaveBeenUsed( } private void assertFieldShouldNotBeUsed( - String fieldName, - boolean equalsChanged, - boolean fieldShouldBeIgnored, - boolean thisFieldIsMarkedAsId, - boolean anotherFieldIsMarkedAsId, - boolean testWithNull - ) { + String fieldName, + boolean equalsChanged, + boolean fieldShouldBeIgnored, + boolean thisFieldIsMarkedAsId, + boolean anotherFieldIsMarkedAsId, + boolean testWithNull) { final String message; if (thisFieldIsMarkedAsId) { - message = - "Significant fields: %% is marked @Id or @EmbeddedId so equals should not use" + - " it, but it does.\n" + - "Suppress Warning.SURROGATE_KEY if you want to use only the @Id or" + - " @EmbeddedId field(s)."; - } else if (anotherFieldIsMarkedAsId) { - message = - "Significant fields: equals should not use %% because Warning.SURROGATE_KEY is" + - " suppressed and it is not marked as @Id or @EmbeddedId, but it does."; - } else { + message = "Significant fields: %% is marked @Id or @EmbeddedId so equals should not use" + + " it, but it does.\nSuppress Warning.SURROGATE_KEY if you want to use only the @Id or" + + " @EmbeddedId field(s)."; + } + else if (anotherFieldIsMarkedAsId) { + message = "Significant fields: equals should not use %% because Warning.SURROGATE_KEY is" + + " suppressed and it is not marked as @Id or @EmbeddedId, but it does."; + } + else { message = "Significant fields: equals should not use %%, but it does."; } - assertTrue( - Formatter.of(message, fieldName), - !fieldShouldBeIgnored || !equalsChanged || testWithNull - ); + assertTrue(Formatter.of(message, fieldName), !fieldShouldBeIgnored || !equalsChanged || testWithNull); } } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/StringFieldCheck.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/StringFieldCheck.java index 0000feb2f..e8ce7b741 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/StringFieldCheck.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/StringFieldCheck.java @@ -19,25 +19,18 @@ public class StringFieldCheck implements FieldCheck { private final ValueProvider valueProvider; private final CachedHashCodeInitializer cachedHashCodeInitializer; - @SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "PrefabValues is inherently mutable." - ) + @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "PrefabValues is inherently mutable.") public StringFieldCheck( - SubjectCreator subjectCreator, - ValueProvider instanceCreator, - CachedHashCodeInitializer cachedHashCodeInitializer - ) { + SubjectCreator subjectCreator, + ValueProvider instanceCreator, + CachedHashCodeInitializer cachedHashCodeInitializer) { this.subjectCreator = subjectCreator; this.valueProvider = instanceCreator; this.cachedHashCodeInitializer = cachedHashCodeInitializer; } @Override - @SuppressFBWarnings( - value = "DM_CONVERT_CASE", - justification = "String prefab values are probably not localized." - ) + @SuppressFBWarnings(value = "DM_CONVERT_CASE", justification = "String prefab values are probably not localized.") public void execute(FieldProbe fieldProbe) { if (String.class.equals(fieldProbe.getType()) && !fieldProbe.isStatic()) { TypeTag string = new TypeTag(String.class); @@ -48,25 +41,24 @@ public void execute(FieldProbe fieldProbe) { try { reference = subjectCreator.withFieldSetTo(fieldProbe.getField(), red.toLowerCase()); copy = subjectCreator.withFieldSetTo(fieldProbe.getField(), red.toUpperCase()); - } catch (ReflectionException ignored) { + } + catch (ReflectionException ignored) { // Differently-cased String is not allowed, so cannot cause problems either. return; } boolean theyAreEqual = reference.equals(copy); - boolean theirHashCodesAreEqual = - cachedHashCodeInitializer.getInitializedHashCode(reference) == - cachedHashCodeInitializer.getInitializedHashCode(copy); + boolean theirHashCodesAreEqual = cachedHashCodeInitializer + .getInitializedHashCode(reference) == cachedHashCodeInitializer.getInitializedHashCode(copy); if (theyAreEqual && !theirHashCodesAreEqual) { fail( - Formatter.of( - ERROR_DOC_TITLE + - ": class uses equalsIgnoreCase to compare String field %%, but hashCode is case-sensitive." + - " Use toUpperCase() to determine the hashCode.", - fieldProbe.getName() - ) - ); + Formatter + .of( + ERROR_DOC_TITLE + + ": class uses equalsIgnoreCase to compare String field %%, but hashCode is case-sensitive." + + " Use toUpperCase() to determine the hashCode.", + fieldProbe.getName())); } } } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/SymmetryFieldCheck.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/SymmetryFieldCheck.java index 1bc2d67ad..4ab70b7d5 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/SymmetryFieldCheck.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/SymmetryFieldCheck.java @@ -11,10 +11,7 @@ public class SymmetryFieldCheck implements FieldCheck { private final SubjectCreator subjectCreator; - @SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "PrefabValues is inherently mutable." - ) + @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "PrefabValues is inherently mutable.") public SymmetryFieldCheck(SubjectCreator subjectCreator) { this.subjectCreator = subjectCreator; } @@ -32,7 +29,6 @@ public void execute(FieldProbe fieldProbe) { private void checkSymmetry(T left, T right) { assertTrue( Formatter.of("Symmetry: objects are not symmetric:\n %%\nand\n %%", left, right), - left.equals(right) == right.equals(left) - ); + left.equals(right) == right.equals(left)); } } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/TransientFieldsCheck.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/TransientFieldsCheck.java index a0f2c9c3b..fb9ed33e9 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/TransientFieldsCheck.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/TransientFieldsCheck.java @@ -17,11 +17,7 @@ public class TransientFieldsCheck implements FieldCheck { private final AnnotationCache annotationCache; @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "A cache is inherently mutable.") - public TransientFieldsCheck( - SubjectCreator subjectCreator, - TypeTag typeTag, - AnnotationCache annotationCache - ) { + public TransientFieldsCheck(SubjectCreator subjectCreator, TypeTag typeTag, AnnotationCache annotationCache) { this.subjectCreator = subjectCreator; this.typeTag = typeTag; this.annotationCache = annotationCache; @@ -33,19 +29,15 @@ public void execute(FieldProbe fieldProbe) { T changed = subjectCreator.withFieldChanged(fieldProbe.getField()); boolean equalsChanged = !reference.equals(changed); - boolean hasAnnotation = annotationCache.hasFieldAnnotation( - typeTag.getType(), - fieldProbe.getName(), - SupportedAnnotations.TRANSIENT - ); + boolean hasAnnotation = annotationCache + .hasFieldAnnotation(typeTag.getType(), fieldProbe.getName(), SupportedAnnotations.TRANSIENT); boolean fieldIsTransient = fieldProbe.isTransient() || hasAnnotation; if (equalsChanged && fieldIsTransient) { fail( - Formatter.of( - "Transient field %% should not be included in equals/hashCode contract.", - fieldProbe.getName() - ) - ); + Formatter + .of( + "Transient field %% should not be included in equals/hashCode contract.", + fieldProbe.getName())); } } } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/TransitivityFieldCheck.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/TransitivityFieldCheck.java index c4b540a96..668fe39f4 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/TransitivityFieldCheck.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/checkers/fieldchecks/TransitivityFieldCheck.java @@ -11,10 +11,7 @@ public class TransitivityFieldCheck implements FieldCheck { private final SubjectCreator subjectCreator; - @SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "PrefabValues is inherently mutable." - ) + @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "PrefabValues is inherently mutable.") public TransitivityFieldCheck(SubjectCreator subjectCreator) { this.subjectCreator = subjectCreator; } @@ -31,14 +28,13 @@ public void execute(FieldProbe fieldProbe) { if (countFalses(x, y, z) == 1) { fail( - Formatter.of( - "Transitivity: two of these three instances are equal to each other," + - " so the third one should be, too:\n- %%\n- %%\n- %%", - a1, - b1, - b2 - ) - ); + Formatter + .of( + "Transitivity: two of these three instances are equal to each other," + + " so the third one should be, too:\n- %%\n- %%\n- %%", + a1, + b1, + b2)); } } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/exceptions/EqualsVerifierInternalBugException.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/exceptions/EqualsVerifierInternalBugException.java index def4b3994..8e7924c0a 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/exceptions/EqualsVerifierInternalBugException.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/exceptions/EqualsVerifierInternalBugException.java @@ -5,7 +5,7 @@ public class EqualsVerifierInternalBugException extends RuntimeException { private static final String BUG = - "This is a bug in EqualsVerifier. Please report this in the issue tracker at https://www.jqno.nl/equalsverifier"; + "This is a bug in EqualsVerifier. Please report this in the issue tracker at https://www.jqno.nl/equalsverifier"; public EqualsVerifierInternalBugException() { super(BUG); diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/exceptions/MessagingException.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/exceptions/MessagingException.java index 23350f2ff..a469229b1 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/exceptions/MessagingException.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/exceptions/MessagingException.java @@ -1,10 +1,9 @@ package nl.jqno.equalsverifier.internal.exceptions; /** - * Superclass for exceptions that exist only to send a message to the user when something goes - * wrong. These exceptions do not need to be included as a cause in the final stack trace. If they - * have a cause, this cause will serve directly as the cause for the final stack trace, instead of - * the exception itself. + * Superclass for exceptions that exist only to send a message to the user when something goes wrong. These exceptions + * do not need to be included as a cause in the final stack trace. If they have a cause, this cause will serve directly + * as the cause for the final stack trace, instead of the exception itself. */ @SuppressWarnings("serial") public abstract class MessagingException extends RuntimeException { diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/exceptions/RecursionException.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/exceptions/RecursionException.java index 1b7d590e4..5ae879a1f 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/exceptions/RecursionException.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/exceptions/RecursionException.java @@ -2,6 +2,7 @@ import java.util.Iterator; import java.util.LinkedHashSet; + import nl.jqno.equalsverifier.internal.SuppressFBWarnings; import nl.jqno.equalsverifier.internal.reflection.TypeTag; @@ -15,13 +16,11 @@ public class RecursionException extends MessagingException { /** * Constructor. * - * @param typeStack A collection of types that have been encountered prior to detecting the - * recursion. + * @param typeStack A collection of types that have been encountered prior to detecting the recursion. */ @SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "There's no such thing as an UnmodifiableLinkedHashSet and we need the ordering." - ) + value = "EI_EXPOSE_REP2", + justification = "There's no such thing as an UnmodifiableLinkedHashSet and we need the ordering.") public RecursionException(LinkedHashSet typeStack) { super(); this.typeStack = typeStack; diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/InstanceCreator.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/InstanceCreator.java index eb79f3b79..a6577170f 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/InstanceCreator.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/InstanceCreator.java @@ -3,6 +3,7 @@ import java.lang.reflect.Field; import java.util.*; import java.util.function.BiConsumer; + import nl.jqno.equalsverifier.internal.reflection.*; import nl.jqno.equalsverifier.internal.util.PrimitiveMappers; import org.objenesis.Objenesis; @@ -19,7 +20,7 @@ public class InstanceCreator { /** * Constructor. * - * @param probe Represents the class to instantiate. + * @param probe Represents the class to instantiate. * @param objenesis To instantiate non-record classes. */ public InstanceCreator(ClassProbe probe, Objenesis objenesis) { @@ -29,9 +30,9 @@ public InstanceCreator(ClassProbe probe, Objenesis objenesis) { } /** - * Creates an instance of the given type, with its field set to the given values. If no value - * is given for a specific field, the field will be set to its default value: null for object - * references, 0 for numbers, false for booleans. + * Creates an instance of the given type, with its field set to the given values. If no value is given for a + * specific field, the field will be set to its default value: null for object references, 0 for numbers, false for + * booleans. * * @param values Values to assign to the instance's fields. * @return An instance with assigned values. @@ -41,8 +42,7 @@ public T instantiate(Map values) { } /** - * Creates a new instance with all fields set to the same value as their counterparts from - * {@code original}. + * Creates a new instance with all fields set to the same value as their counterparts from {@code original}. * * @param original The instance to copy. * @return A copy of the given original. @@ -65,10 +65,7 @@ private T createRecordInstance(Map values) { private T createClassInstance(Map values) { T instance = instantiator.instantiate(); - traverseFields( - values, - (f, v) -> new FieldMutator(FieldProbe.of(f)).setNewValue(instance, v) - ); + traverseFields(values, (f, v) -> new FieldMutator(FieldProbe.of(f)).setNewValue(instance, v)); return instance; } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/JavaApiPrefabValues.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/JavaApiPrefabValues.java index 65e710c2e..09fc1b63f 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/JavaApiPrefabValues.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/JavaApiPrefabValues.java @@ -28,6 +28,7 @@ import java.util.concurrent.locks.StampedLock; import java.util.function.Supplier; import java.util.regex.Pattern; + import nl.jqno.equalsverifier.internal.SuppressFBWarnings; import nl.jqno.equalsverifier.internal.instantiation.vintage.FactoryCache; import nl.jqno.equalsverifier.internal.instantiation.vintage.VintageValueProvider; @@ -39,47 +40,32 @@ /** * Creates instances of classes for use in a {@link VintageValueProvider} object. * - *

Contains hand-made instances of well-known Java API classes that cannot be instantiated - * dynamically because of an internal infinite recursion of types, or other issues. + *

+ * Contains hand-made instances of well-known Java API classes that cannot be instantiated dynamically because of an + * internal infinite recursion of types, or other issues. */ @SuppressFBWarnings( - value = "SIC_INNER_SHOULD_BE_STATIC_ANON", - justification = "That would be dozens of separate classes" -) + value = "SIC_INNER_SHOULD_BE_STATIC_ANON", + justification = "That would be dozens of separate classes") public final class JavaApiPrefabValues { private static final String JAVAFX_COLLECTIONS_PACKAGE = "javafx.collections."; private static final String JAVAFX_PROPERTY_PACKAGE = "javafx.beans.property."; private static final String GUAVA_PACKAGE = "com.google.common.collect."; private static final String JODA_PACKAGE = "org.joda.time."; - private static final ExternalFactory AWT_FACTORY = new ExternalFactory<>( - "AwtFactoryProvider" - ); - private static final ExternalFactory JAVAFX_FACTORY = new ExternalFactory<>( - "JavaFxFactoryProvider" - ); - private static final ExternalFactory JAVAX_FACTORY = new ExternalFactory<>( - "JavaxFactoryProvider" - ); - private static final ExternalFactory GUAVA_FACTORY = new ExternalFactory<>( - "GuavaFactoryProvider" - ); - private static final ExternalFactory JODA_FACTORY = new ExternalFactory<>( - "JodaFactoryProvider" - ); - private static final ExternalFactory RMI_FACTORY = new ExternalFactory<>( - "RmiFactoryProvider" - ); - - private static final Comparator OBJECT_COMPARATOR = Comparator.comparingInt( - Object::hashCode - ); + private static final ExternalFactory AWT_FACTORY = new ExternalFactory<>("AwtFactoryProvider"); + private static final ExternalFactory JAVAFX_FACTORY = new ExternalFactory<>("JavaFxFactoryProvider"); + private static final ExternalFactory JAVAX_FACTORY = new ExternalFactory<>("JavaxFactoryProvider"); + private static final ExternalFactory GUAVA_FACTORY = new ExternalFactory<>("GuavaFactoryProvider"); + private static final ExternalFactory JODA_FACTORY = new ExternalFactory<>("JodaFactoryProvider"); + private static final ExternalFactory RMI_FACTORY = new ExternalFactory<>("RmiFactoryProvider"); + + private static final Comparator OBJECT_COMPARATOR = Comparator.comparingInt(Object::hashCode); private final FactoryCache factoryCache; private enum Dummy { - RED, - BLUE + RED, BLUE } /** Private constructor. Use {@link #build()}. */ @@ -88,8 +74,7 @@ private JavaApiPrefabValues(FactoryCache factoryCache) { } /** - * Creates a FactoryCache pre-populated with instances of Java API classes that cannot be - * instantiated dynamically. + * Creates a FactoryCache pre-populated with instances of Java API classes that cannot be instantiated dynamically. * * @return A pre-populated {@link FactoryCache}. */ @@ -127,9 +112,8 @@ private void addJavaClasses() { } @SuppressFBWarnings( - value = { "DM_BOOLEAN_CTOR", "DM_NUMBER_CTOR", "DM_FP_NUMBER_CTOR", "DM_STRING_CTOR" }, - justification = "We really do need a separate instances with the same value" - ) + value = { "DM_BOOLEAN_CTOR", "DM_NUMBER_CTOR", "DM_FP_NUMBER_CTOR", "DM_STRING_CTOR" }, + justification = "We really do need a separate instances with the same value") private void addPrimitiveClasses() { addValues(boolean.class, true, false, true); addValues(byte.class, (byte) 1, (byte) 2, (byte) 1); @@ -156,35 +140,19 @@ private void addPrimitiveClasses() { // CHECKSTYLE OFF: ExecutableStatementCount @SuppressFBWarnings( - value = { "DMI_HARDCODED_ABSOLUTE_FILENAME", "DM_USELESS_THREAD" }, - justification = "We just need an instance of File and Thread; they're not for actual use." - ) + value = { "DMI_HARDCODED_ABSOLUTE_FILENAME", "DM_USELESS_THREAD" }, + justification = "We just need an instance of File and Thread; they're not for actual use.") private void addCommonClasses() { addValues(BigDecimal.class, BigDecimal.ZERO, BigDecimal.ONE, BigDecimal.ZERO); addValues(BigInteger.class, BigInteger.ZERO, BigInteger.ONE, BigInteger.ZERO); - addValues( - Charset.class, - StandardCharsets.UTF_8, - StandardCharsets.US_ASCII, - StandardCharsets.UTF_8 - ); + addValues(Charset.class, StandardCharsets.UTF_8, StandardCharsets.US_ASCII, StandardCharsets.UTF_8); addValues(File.class, new File(""), new File("/"), new File("")); addValues(Formatter.class, new Formatter(), new Formatter(), new Formatter()); addValues(Locale.class, new Locale("nl"), new Locale("hu"), new Locale("nl")); - addValues( - Pattern.class, - Pattern.compile("one"), - Pattern.compile("two"), - Pattern.compile("one") - ); + addValues(Pattern.class, Pattern.compile("one"), Pattern.compile("two"), Pattern.compile("one")); addValues(Scanner.class, new Scanner("one"), new Scanner("two"), new Scanner("one")); addValues(StampedLock.class, new StampedLock(), new StampedLock(), new StampedLock()); - addValues( - StringBuilder.class, - new StringBuilder("one"), - new StringBuilder("two"), - new StringBuilder("three") - ); + addValues(StringBuilder.class, new StringBuilder("one"), new StringBuilder("two"), new StringBuilder("three")); addValues(Thread.class, new Thread("one"), new Thread("two"), new Thread("one")); addValues(Throwable.class, new Throwable(), new Throwable(), new Throwable()); addValues(URI.class, URI.create("x"), URI.create("y"), URI.create("x")); @@ -192,27 +160,16 @@ private void addCommonClasses() { addValues(PrintStream.class, System.out, System.err, System.out); rethrow( - () -> - addValues( - URL.class, - new URL("http://example.com"), - new URL("http://localhost"), - new URL("http://example.com") - ), - e -> "Can't add prefab values for java.net.URL" - ); - - addFactory( - CompletableFuture.class, - simple(ignored -> new CompletableFuture<>(), CompletableFuture::new) - ); + () -> addValues( + URL.class, + new URL("http://example.com"), + new URL("http://localhost"), + new URL("http://example.com")), + e -> "Can't add prefab values for java.net.URL"); + + addFactory(CompletableFuture.class, simple(ignored -> new CompletableFuture<>(), CompletableFuture::new)); addFactory(Optional.class, simple(Optional::of, Optional::empty)); - addValues( - OptionalDouble.class, - OptionalDouble.of(0.5), - OptionalDouble.of(1.0), - OptionalDouble.of(0.5) - ); + addValues(OptionalDouble.class, OptionalDouble.of(0.5), OptionalDouble.of(1.0), OptionalDouble.of(0.5)); addValues(OptionalInt.class, OptionalInt.of(1), OptionalInt.of(2), OptionalInt.of(1)); addValues(OptionalLong.class, OptionalLong.of(1), OptionalLong.of(2), OptionalLong.of(1)); addFactory(Supplier.class, simple(a -> () -> a, () -> () -> null)); @@ -220,8 +177,7 @@ private void addCommonClasses() { Currency.class, Currency.getInstance("USD"), Currency.getInstance("EUR"), - Currency.getInstance("JPY") - ); + Currency.getInstance("JPY")); Semaphore redSemaphore = new Semaphore(1); Semaphore blueSemaphore = new Semaphore(1); @@ -244,34 +200,25 @@ private void addDateTimeClasses() { Calendar.class, new GregorianCalendar(2010, Calendar.AUGUST, 4), new GregorianCalendar(2010, Calendar.AUGUST, 5), - new GregorianCalendar(2010, Calendar.AUGUST, 4) - ); - addValues( - Clock.class, - Clock.systemUTC(), - Clock.system(ZoneId.of("-10")), - Clock.systemUTC() - ); + new GregorianCalendar(2010, Calendar.AUGUST, 4)); + addValues(Clock.class, Clock.systemUTC(), Clock.system(ZoneId.of("-10")), Clock.systemUTC()); addValues(Date.class, new Date(0), new Date(1), new Date(0)); addValues( DateFormat.class, DateFormat.getTimeInstance(), DateFormat.getDateInstance(), - DateFormat.getTimeInstance() - ); + DateFormat.getTimeInstance()); addValues( DateTimeFormatter.class, DateTimeFormatter.ISO_TIME, DateTimeFormatter.ISO_DATE, - DateTimeFormatter.ISO_TIME - ); + DateTimeFormatter.ISO_TIME); addValues(Duration.class, Duration.ZERO, Duration.ofDays(1L), Duration.ZERO); addValues( GregorianCalendar.class, new GregorianCalendar(2010, Calendar.AUGUST, 4), new GregorianCalendar(2010, Calendar.AUGUST, 5), - new GregorianCalendar(2010, Calendar.AUGUST, 4) - ); + new GregorianCalendar(2010, Calendar.AUGUST, 4)); addValues(Instant.class, Instant.MIN, Instant.MAX, Instant.MIN); addValues(LocalDateTime.class, LocalDateTime.MIN, LocalDateTime.MAX, LocalDateTime.MIN); addValues(LocalDate.class, LocalDate.MIN, LocalDate.MAX, LocalDate.MIN); @@ -280,50 +227,27 @@ private void addDateTimeClasses() { addValues(OffsetDateTime.class, OffsetDateTime.MIN, OffsetDateTime.MAX, OffsetDateTime.MIN); addValues(OffsetTime.class, OffsetTime.MIN, OffsetTime.MAX, OffsetTime.MIN); addValues(Period.class, Period.ZERO, Period.of(1, 1, 1), Period.ZERO); - addValues( - DecimalFormat.class, - new DecimalFormat("x0.0"), - new DecimalFormat("y0.0"), - new DecimalFormat("x0.0") - ); - addValues( - NumberFormat.class, - new DecimalFormat("x0.0"), - new DecimalFormat("y0.0"), - new DecimalFormat("x0.0") - ); + addValues(DecimalFormat.class, new DecimalFormat("x0.0"), new DecimalFormat("y0.0"), new DecimalFormat("x0.0")); + addValues(NumberFormat.class, new DecimalFormat("x0.0"), new DecimalFormat("y0.0"), new DecimalFormat("x0.0")); addValues( SimpleDateFormat.class, new SimpleDateFormat("yMd"), new SimpleDateFormat("dMy"), - new SimpleDateFormat("yMd") - ); + new SimpleDateFormat("yMd")); addValues( TimeZone.class, TimeZone.getTimeZone("GMT+1"), TimeZone.getTimeZone("GMT+2"), - TimeZone.getTimeZone("GMT+1") - ); + TimeZone.getTimeZone("GMT+1")); addValues(Year.class, Year.of(2000), Year.of(2010), Year.of(2000)); - addValues( - YearMonth.class, - YearMonth.of(2000, 1), - YearMonth.of(2010, 12), - YearMonth.of(2000, 1) - ); + addValues(YearMonth.class, YearMonth.of(2000, 1), YearMonth.of(2010, 12), YearMonth.of(2000, 1)); addValues(ZoneId.class, ZoneId.of("+1"), ZoneId.of("-10"), ZoneId.of("+1")); - addValues( - ZoneOffset.class, - ZoneOffset.ofHours(1), - ZoneOffset.ofHours(-1), - ZoneOffset.ofHours(1) - ); + addValues(ZoneOffset.class, ZoneOffset.ofHours(1), ZoneOffset.ofHours(-1), ZoneOffset.ofHours(1)); addValues( ZonedDateTime.class, ZonedDateTime.parse("2017-12-13T10:15:30+01:00"), ZonedDateTime.parse("2016-11-12T09:14:29-01:00"), - ZonedDateTime.parse("2017-12-13T10:15:30+01:00") - ); + ZonedDateTime.parse("2017-12-13T10:15:30+01:00")); } private void addUncommonClasses() { @@ -338,28 +262,24 @@ private void addUncommonClasses() { sqlDate.resolve(), sqlDate.instantiate(classes(long.class), objects(1337)), sqlDate.instantiate(classes(long.class), objects(42)), - sqlDate.instantiate(classes(long.class), objects(1337)) - ); + sqlDate.instantiate(classes(long.class), objects(1337))); addValues( sqlTime.resolve(), sqlTime.instantiate(classes(long.class), objects(1337)), sqlTime.instantiate(classes(long.class), objects(42)), - sqlTime.instantiate(classes(long.class), objects(1337)) - ); + sqlTime.instantiate(classes(long.class), objects(1337))); addValues( sqlTimestamp.resolve(), sqlTimestamp.instantiate(classes(long.class), objects(1337)), sqlTimestamp.instantiate(classes(long.class), objects(42)), - sqlTimestamp.instantiate(classes(long.class), objects(1337)) - ); + sqlTimestamp.instantiate(classes(long.class), objects(1337))); addValues(EventObject.class, new EventObject(1), new EventObject(2), new EventObject(1)); addValues( InetSocketAddress.class, InetSocketAddress.createUnresolved("localhost", 8080), InetSocketAddress.createUnresolved("127.0.0.1", 8080), - InetSocketAddress.createUnresolved("localhost", 8080) - ); + InetSocketAddress.createUnresolved("localhost", 8080)); // Constructing InetAddress reflectively, because it might throw an awkward exception // otherwise. @@ -370,35 +290,26 @@ private void addUncommonClasses() { inetAddress.resolve(), inetAddress.callFactory("getByName", classes(String.class), objects("127.0.0.1")), inetAddress.callFactory("getByName", classes(String.class), objects("127.0.0.42")), - inetAddress.callFactory("getByName", classes(String.class), objects("127.0.0.1")) - ); + inetAddress.callFactory("getByName", classes(String.class), objects("127.0.0.1"))); addValues( inet4Address.resolve(), inet4Address.callFactory("getByName", classes(String.class), objects("127.0.0.1")), inet4Address.callFactory("getByName", classes(String.class), objects("127.0.0.42")), - inet4Address.callFactory("getByName", classes(String.class), objects("127.0.0.1")) - ); + inet4Address.callFactory("getByName", classes(String.class), objects("127.0.0.1"))); addValues( inet6Address.resolve(), inet6Address.callFactory("getByName", classes(String.class), objects("::1")), inet6Address.callFactory("getByName", classes(String.class), objects("::")), - inet6Address.callFactory("getByName", classes(String.class), objects("::1")) - ); + inet6Address.callFactory("getByName", classes(String.class), objects("::1"))); } @SuppressWarnings({ "unchecked", "rawtypes" }) private void addCollection() { - addFactory( - Iterable.class, - simple( - a -> { - Collection coll = new ArrayList<>(); - coll.add(a); - return coll; - }, - ArrayList::new - ) - ); + addFactory(Iterable.class, simple(a -> { + Collection coll = new ArrayList<>(); + coll.add(a); + return coll; + }, ArrayList::new)); addFactory(Collection.class, collection(ArrayList::new)); } @@ -417,10 +328,7 @@ private void addMaps() { addFactory(Map.class, map(HashMap::new)); addFactory(SortedMap.class, map(() -> new TreeMap<>(OBJECT_COMPARATOR))); addFactory(NavigableMap.class, map(() -> new TreeMap<>(OBJECT_COMPARATOR))); - addFactory( - ConcurrentNavigableMap.class, - map(() -> new ConcurrentSkipListMap<>(OBJECT_COMPARATOR)) - ); + addFactory(ConcurrentNavigableMap.class, map(() -> new ConcurrentSkipListMap<>(OBJECT_COMPARATOR))); addFactory(ConcurrentHashMap.class, map(ConcurrentHashMap::new)); addFactory(HashMap.class, map(HashMap::new)); addFactory(Hashtable.class, map(Hashtable::new)); @@ -444,8 +352,7 @@ private void addSets() { BitSet.class, BitSet.valueOf(new byte[] { 0 }), BitSet.valueOf(new byte[] { 1 }), - BitSet.valueOf(new byte[] { 0 }) - ); + BitSet.valueOf(new byte[] { 0 })); } @SuppressWarnings({ "unchecked", "rawtypes" }) @@ -458,16 +365,8 @@ private void addQueues() { addFactory(ConcurrentLinkedQueue.class, collection(ConcurrentLinkedQueue::new)); addFactory(DelayQueue.class, collection(DelayQueue::new)); addFactory(LinkedBlockingQueue.class, collection(() -> new LinkedBlockingQueue(1))); - addFactory( - PriorityBlockingQueue.class, - collection(() -> new PriorityBlockingQueue<>(1, OBJECT_COMPARATOR)) - ); - addValues( - SynchronousQueue.class, - new SynchronousQueue<>(), - new SynchronousQueue<>(), - new SynchronousQueue<>() - ); + addFactory(PriorityBlockingQueue.class, collection(() -> new PriorityBlockingQueue<>(1, OBJECT_COMPARATOR))); + addValues(SynchronousQueue.class, new SynchronousQueue<>(), new SynchronousQueue<>(), new SynchronousQueue<>()); } private void addNioBuffers() { @@ -475,50 +374,38 @@ private void addNioBuffers() { Buffer.class, ByteBuffer.wrap(new byte[] { 0 }), ByteBuffer.wrap(new byte[] { 1 }), - ByteBuffer.wrap(new byte[] { 0 }) - ); + ByteBuffer.wrap(new byte[] { 0 })); addValues( ByteBuffer.class, ByteBuffer.wrap(new byte[] { 0 }), ByteBuffer.wrap(new byte[] { 1 }), - ByteBuffer.wrap(new byte[] { 0 }) - ); - addValues( - CharBuffer.class, - CharBuffer.wrap("a"), - CharBuffer.wrap("b"), - CharBuffer.wrap("a") - ); + ByteBuffer.wrap(new byte[] { 0 })); + addValues(CharBuffer.class, CharBuffer.wrap("a"), CharBuffer.wrap("b"), CharBuffer.wrap("a")); addValues( DoubleBuffer.class, DoubleBuffer.wrap(new double[] { 0.0 }), DoubleBuffer.wrap(new double[] { 1.0 }), - DoubleBuffer.wrap(new double[] { 0.0 }) - ); + DoubleBuffer.wrap(new double[] { 0.0 })); addValues( FloatBuffer.class, FloatBuffer.wrap(new float[] { 0.0f }), FloatBuffer.wrap(new float[] { 1.0f }), - FloatBuffer.wrap(new float[] { 0.0f }) - ); + FloatBuffer.wrap(new float[] { 0.0f })); addValues( IntBuffer.class, IntBuffer.wrap(new int[] { 0 }), IntBuffer.wrap(new int[] { 1 }), - IntBuffer.wrap(new int[] { 0 }) - ); + IntBuffer.wrap(new int[] { 0 })); addValues( LongBuffer.class, LongBuffer.wrap(new long[] { 0 }), LongBuffer.wrap(new long[] { 1 }), - LongBuffer.wrap(new long[] { 0 }) - ); + LongBuffer.wrap(new long[] { 0 })); addValues( ShortBuffer.class, ShortBuffer.wrap(new short[] { 0 }), ShortBuffer.wrap(new short[] { 1 }), - ShortBuffer.wrap(new short[] { 0 }) - ); + ShortBuffer.wrap(new short[] { 0 })); } private void addExceptions() { @@ -532,27 +419,16 @@ private void addExceptions() { RuntimeException redRuntimeException = new RuntimeException(); RuntimeException blueRuntimeException = new RuntimeException(); - addValues( - RuntimeException.class, - redRuntimeException, - blueRuntimeException, - redRuntimeException - ); + addValues(RuntimeException.class, redRuntimeException, blueRuntimeException, redRuntimeException); } @SuppressWarnings("unused") private static class JavaApiReflectionClassesContainer { - @SuppressFBWarnings( - value = "UUF_UNUSED_FIELD", - justification = "These fields are accessed through reflection" - ) + @SuppressFBWarnings(value = "UUF_UNUSED_FIELD", justification = "These fields are accessed through reflection") Object a; - @SuppressFBWarnings( - value = "UUF_UNUSED_FIELD", - justification = "These fields are accessed through reflection" - ) + @SuppressFBWarnings(value = "UUF_UNUSED_FIELD", justification = "These fields are accessed through reflection") Object b; public JavaApiReflectionClassesContainer() {} @@ -567,109 +443,67 @@ void m2() {} private void addReflectionClasses() { addValues(Class.class, Class.class, Object.class, Class.class); - rethrow( - () -> { - Field f1 = JavaApiReflectionClassesContainer.class.getDeclaredField("a"); - Field f2 = JavaApiReflectionClassesContainer.class.getDeclaredField("b"); - addValues(Field.class, f1, f2, f1); - }, - e -> "Can't add prefab values for java.lang.reflect.Field" - ); + rethrow(() -> { + Field f1 = JavaApiReflectionClassesContainer.class.getDeclaredField("a"); + Field f2 = JavaApiReflectionClassesContainer.class.getDeclaredField("b"); + addValues(Field.class, f1, f2, f1); + }, e -> "Can't add prefab values for java.lang.reflect.Field"); - rethrow( - () -> { - Constructor c1 = - JavaApiReflectionClassesContainer.class.getDeclaredConstructor(); - Constructor c2 = - JavaApiReflectionClassesContainer.class.getDeclaredConstructor(Object.class); - addValues(Constructor.class, c1, c2, c1); - }, - e -> "Can't add prefab values for java.lang.reflect.Constructor" - ); + rethrow(() -> { + Constructor c1 = JavaApiReflectionClassesContainer.class.getDeclaredConstructor(); + Constructor c2 = JavaApiReflectionClassesContainer.class.getDeclaredConstructor(Object.class); + addValues(Constructor.class, c1, c2, c1); + }, e -> "Can't add prefab values for java.lang.reflect.Constructor"); - rethrow( - () -> { - Method m1 = JavaApiReflectionClassesContainer.class.getDeclaredMethod("m1"); - Method m2 = JavaApiReflectionClassesContainer.class.getDeclaredMethod("m2"); - addValues(Method.class, m1, m2, m1); - }, - e -> "Can't add prefab values for java.lang.reflect.Method" - ); + rethrow(() -> { + Method m1 = JavaApiReflectionClassesContainer.class.getDeclaredMethod("m1"); + Method m2 = JavaApiReflectionClassesContainer.class.getDeclaredMethod("m2"); + addValues(Method.class, m1, m2, m1); + }, e -> "Can't add prefab values for java.lang.reflect.Method"); } @SuppressWarnings({ "unchecked", "rawtypes" }) private void addAtomicClasses() { - addValues( - AtomicBoolean.class, - new AtomicBoolean(true), - new AtomicBoolean(false), - new AtomicBoolean(true) - ); - addValues( - AtomicInteger.class, - new AtomicInteger(1), - new AtomicInteger(2), - new AtomicInteger(1) - ); + addValues(AtomicBoolean.class, new AtomicBoolean(true), new AtomicBoolean(false), new AtomicBoolean(true)); + addValues(AtomicInteger.class, new AtomicInteger(1), new AtomicInteger(2), new AtomicInteger(1)); addValues( AtomicIntegerArray.class, new AtomicIntegerArray(new int[] { 1 }), new AtomicIntegerArray(new int[] { 2 }), - new AtomicIntegerArray(new int[] { 1 }) - ); + new AtomicIntegerArray(new int[] { 1 })); addValues(AtomicLong.class, new AtomicLong(1L), new AtomicLong(2L), new AtomicLong(1L)); addValues( AtomicLongArray.class, new AtomicLongArray(new long[] { 1L }), new AtomicLongArray(new long[] { 2L }), - new AtomicLongArray(new long[] { 1L }) - ); - addFactory( - AtomicMarkableReference.class, - simple(r -> new AtomicMarkableReference(r, true), null) - ); + new AtomicLongArray(new long[] { 1L })); + addFactory(AtomicMarkableReference.class, simple(r -> new AtomicMarkableReference(r, true), null)); addFactory(AtomicReference.class, simple(AtomicReference::new, null)); - addFactory( - AtomicStampedReference.class, - simple(r -> new AtomicStampedReference(r, 0), null) - ); - addFactory( - AtomicReferenceArray.class, - (tag, pv, stack) -> { - TypeTag y = tag.getGenericTypes().get(0); - Object[] red = new Object[] { pv.giveRed(y) }; - Object[] blue = new Object[] { pv.giveBlue(y) }; - Object[] redCopy = new Object[] { pv.giveRedCopy(y) }; - return Tuple.of( - new AtomicReferenceArray(red), - new AtomicReferenceArray(blue), - new AtomicReferenceArray(redCopy) - ); - } - ); + addFactory(AtomicStampedReference.class, simple(r -> new AtomicStampedReference(r, 0), null)); + addFactory(AtomicReferenceArray.class, (tag, pv, stack) -> { + TypeTag y = tag.getGenericTypes().get(0); + Object[] red = new Object[] { pv.giveRed(y) }; + Object[] blue = new Object[] { pv.giveBlue(y) }; + Object[] redCopy = new Object[] { pv.giveRedCopy(y) }; + return Tuple + .of( + new AtomicReferenceArray(red), + new AtomicReferenceArray(blue), + new AtomicReferenceArray(redCopy)); + }); DoubleAdder redDoubleAdder = new DoubleAdder(); DoubleAdder blueDoubleAdder = new DoubleAdder(); addValues(DoubleAdder.class, redDoubleAdder, blueDoubleAdder, redDoubleAdder); DoubleAccumulator redDoubleAccumulator = new DoubleAccumulator((a, b) -> a + b, 0.0); DoubleAccumulator blueDoubleAccumulator = new DoubleAccumulator((a, b) -> a * b, 1.0); - addValues( - DoubleAccumulator.class, - redDoubleAccumulator, - blueDoubleAccumulator, - redDoubleAccumulator - ); + addValues(DoubleAccumulator.class, redDoubleAccumulator, blueDoubleAccumulator, redDoubleAccumulator); LongAdder redLongAdder = new LongAdder(); LongAdder blueLongAdder = new LongAdder(); addValues(LongAdder.class, redLongAdder, blueLongAdder, redLongAdder); LongAccumulator redLongAccumulator = new LongAccumulator((a, b) -> a + b, 0); LongAccumulator blueLongAccumulator = new LongAccumulator((a, b) -> a * b, 1); - addValues( - LongAccumulator.class, - redLongAccumulator, - blueLongAccumulator, - redLongAccumulator - ); + addValues(LongAccumulator.class, redLongAccumulator, blueLongAccumulator, redLongAccumulator); } private void addAncientJavaApiClasses() { @@ -685,9 +519,7 @@ private void addAncientJavaApiClasses() { values( new PropertyChangeSupport("this"), new PropertyChangeSupport("that"), - new PropertyChangeSupport("this") - ) - ); + new PropertyChangeSupport("this"))); addLazyFactory("java.rmi.dgc.VMID", RMI_FACTORY); addLazyFactory("java.rmi.server.UID", RMI_FACTORY); diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/SubjectCreator.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/SubjectCreator.java index 3e5e59b6c..62c932418 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/SubjectCreator.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/SubjectCreator.java @@ -3,6 +3,7 @@ import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; + import nl.jqno.equalsverifier.internal.SuppressFBWarnings; import nl.jqno.equalsverifier.internal.exceptions.ModuleException; import nl.jqno.equalsverifier.internal.reflection.*; @@ -11,8 +12,7 @@ import org.objenesis.Objenesis; /** - * Creates a subject, i.e. an instance of the class that is currently being tested by - * EqualsVerifier. + * Creates a subject, i.e. an instance of the class that is currently being tested by EqualsVerifier. */ public class SubjectCreator { @@ -28,18 +28,17 @@ public class SubjectCreator { /** * Constructor. * - * @param config A configuration object. + * @param config A configuration object. * @param valueProvider To provide values for the fields of the subject. - * @param fieldCache Prepared values for the fields of the subject. - * @param objenesis Needed by InstanceCreator to instantiate non-record classes. + * @param fieldCache Prepared values for the fields of the subject. + * @param objenesis Needed by InstanceCreator to instantiate non-record classes. */ @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "A cache is inherently mutable") public SubjectCreator( - Configuration config, - ValueProvider valueProvider, - FieldCache fieldCache, - Objenesis objenesis - ) { + Configuration config, + ValueProvider valueProvider, + FieldCache fieldCache, + Objenesis objenesis) { this.typeTag = config.getTypeTag(); this.type = typeTag.getType(); this.config = config; @@ -51,9 +50,8 @@ public SubjectCreator( } /** - * Creates an instance with all values set with prefab values assigned to their respective field - * names or types, or, if no prefab values are given, values created by the - * {@link ValueProvider}. + * Creates an instance with all values set with prefab values assigned to their respective field names or types, or, + * if no prefab values are given, values created by the {@link ValueProvider}. * * @return A plain instance. */ @@ -62,8 +60,8 @@ public T plain() { } /** - * Creates a {@link #plain()} instance, but with the given field set to its type's default - * value: null for object references, 0 for numbers, false for booleans. + * Creates a {@link #plain()} instance, but with the given field set to its type's default value: null for object + * references, 0 for numbers, false for booleans. * * @param field The field to default. * @return A plain instance with a field defaulted. @@ -73,8 +71,8 @@ public T withFieldDefaulted(Field field) { } /** - * Creates an instance with all values set to their type's default value: null for object - * references, 0 for numbers, false for booleans. + * Creates an instance with all values set to their type's default value: null for object references, 0 for numbers, + * false for booleans. * * @return An instance with all fields defaulted. */ @@ -87,9 +85,8 @@ public T withAllFieldsDefaulted() { } /** - * Creates an instance with all values set to their type's default value: null for object - * references, 0 for numbers, false for booleans; except for the given field which is set - * to its {@link #plain()} value. + * Creates an instance with all values set to their type's default value: null for object references, 0 for numbers, + * false for booleans; except for the given field which is set to its {@link #plain()} value. * * @param field The field that should not be defaulted. * @return An instance with all fields defaulted except for {@code field}. @@ -144,9 +141,8 @@ public T withAllFieldsChanged() { } /** - * Creates a {@link #plain()} instance, but with all fields that are declared in the current - * class set to another value. Fields coming from the superclasses get their {@link #plain()} - * value. + * Creates a {@link #plain()} instance, but with all fields that are declared in the current class set to another + * value. Fields coming from the superclasses get their {@link #plain()} value. * * @return A plain instance with all non-inherited fields changed. */ @@ -160,8 +156,7 @@ public T withAllFieldsShallowlyChanged() { } /** - * Creates a new instance with all fields set to the same value as their counterparts from - * {@code original}. + * Creates a new instance with all fields set to the same value as their counterparts from {@code original}. * * @param original The instance to copy. * @return A copy of the given original. @@ -171,29 +166,26 @@ public T copy(T original) { } /** - * Creates a new instance of the superclass of the current class, with all fields that exist - * within that superclass set to the same value as their counterparts from {@code original}. + * Creates a new instance of the superclass of the current class, with all fields that exist within that superclass + * set to the same value as their counterparts from {@code original}. * * @param original The instance to copy. * @return An instance of the givenoriginal's superclass, but otherwise a copy of the original. */ public Object copyIntoSuperclass(T original) { - InstanceCreator superCreator = new InstanceCreator<>( - new ClassProbe<>(type.getSuperclass()), - objenesis - ); + InstanceCreator superCreator = + new InstanceCreator<>(new ClassProbe<>(type.getSuperclass()), objenesis); return superCreator.copy(original); } /** - * Creates a new instance of the given subclass of the current class, with all fields that also - * exist in the current class set to the same value as their counterparts from - * {@code original}. All fields declared in the subclass are set to their {@link #plain()} - * values. + * Creates a new instance of the given subclass of the current class, with all fields that also exist in the current + * class set to the same value as their counterparts from {@code original}. All fields declared in the subclass are + * set to their {@link #plain()} values. * - * @param A subtype of original's type. + * @param A subtype of original's type. * @param original The instance to copy. - * @param subType A subtype of original's type. + * @param subType A subtype of original's type. * @return An instance of the given subType, but otherwise a copy of the given original. */ public S copyIntoSubclass(T original, Class subType) { @@ -210,8 +202,7 @@ private Map determineValues(Map givens) { Map values = new HashMap<>(givens); for (Field f : fields()) { boolean fieldIsAbsent = !values.containsKey(f); - boolean fieldCannotBeNull = - values.get(f) == null && !FieldProbe.of(f).canBeDefault(config); + boolean fieldCannotBeNull = values.get(f) == null && !FieldProbe.of(f).canBeDefault(config); if (fieldIsAbsent || fieldCannotBeNull) { Object value = valuesFor(f).getRed(); values.put(f, value); @@ -248,17 +239,11 @@ private Tuple valuesFor(Field f) { Tuple tuple = valueProvider.provideOrThrow(fieldTag); fieldCache.put(fieldName, tuple); return tuple; - } catch (ModuleException e) { - throw new ModuleException( - "Field " + - f.getName() + - " of type " + - f.getType().getName() + - " is not accessible via the Java Module System.\nConsider opening the module that contains it, or add prefab values for type " + - f.getType().getName() + - ".", - e - ); + } + catch (ModuleException e) { + throw new ModuleException("Field " + f.getName() + " of type " + f.getType().getName() + + " is not accessible via the Java Module System.\nConsider opening the module that contains it, or add prefab values for type " + + f.getType().getName() + ".", e); } } } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/ValueProvider.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/ValueProvider.java index e2482c139..959673b23 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/ValueProvider.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/ValueProvider.java @@ -1,6 +1,7 @@ package nl.jqno.equalsverifier.internal.instantiation; import java.util.Optional; + import nl.jqno.equalsverifier.internal.exceptions.NoValueException; import nl.jqno.equalsverifier.internal.reflection.Tuple; import nl.jqno.equalsverifier.internal.reflection.TypeTag; @@ -8,11 +9,13 @@ /** * Creator of prefabricated instances of classes. * - *

These instances are intended to be used to populate a subject, i.e. the class that is - * currently being tested by EqualsVerifier. + *

+ * These instances are intended to be used to populate a subject, i.e. the class that is currently being tested by + * EqualsVerifier. * - *

Only creates values ones, and caches them once they've been created. Takes generics into - * account; i.e., {@code List} is different from {@code List}. + *

+ * Only creates values ones, and caches them once they've been created. Takes generics into account; i.e., + * {@code List} is different from {@code List}. */ public interface ValueProvider { /** @@ -20,19 +23,16 @@ public interface ValueProvider { * * @param The returned tuple will have this generic type. * @param tag A description of the desired type, including generic parameters. - * @return A tuple of two different values of the given type, or an empty Optional if none - * could be found. + * @return A tuple of two different values of the given type, or an empty Optional if none could be found. */ Optional> provide(TypeTag tag); /** - * Returns a tuple of prefabricated values of the specified type, or, if none exists, throws a - * NoValueException. + * Returns a tuple of prefabricated values of the specified type, or, if none exists, throws a NoValueException. * * @param The returned tuple will have this generic type. * @param tag A description of the desired type, including generic parameters. - * @return A tuple of two different values of the given type, or an empty Optional if none - * could be found. + * @return A tuple of two different values of the given type, or an empty Optional if none could be found. * @throws NoValueException if no value could be found for the given tag. */ default Tuple provideOrThrow(TypeTag tag) { diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/FactoryCache.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/FactoryCache.java index a07a000cc..e1ca7ce46 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/FactoryCache.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/FactoryCache.java @@ -2,22 +2,23 @@ import java.util.HashMap; import java.util.Map; + import nl.jqno.equalsverifier.internal.instantiation.vintage.prefabvalues.factories.PrefabValueFactory; /** Contains a cache of factories, for {@link VintageValueProvider}. */ public class FactoryCache { /** - * We store Strings instead of Classes, so that the cache can be lazy and initializers won't be - * called until the class is actually needed. + * We store Strings instead of Classes, so that the cache can be lazy and initializers won't be called until the + * class is actually needed. */ private final Map> cache = new HashMap<>(); /** * Adds the given factory to the cache and associates it with the given type. * - * @param The type of the factory. - * @param type The type to associate with the factory. + * @param The type of the factory. + * @param type The type to associate with the factory. * @param factory The factory to associate with the type. */ public void put(Class type, PrefabValueFactory factory) { @@ -29,9 +30,9 @@ public void put(Class type, PrefabValueFactory factory) { /** * Adds the given factory to the cache and associates it with the given type name. * - * @param Should match {@code typeName}. + * @param Should match {@code typeName}. * @param typeName The fully qualified name of the type. - * @param factory The factory to associate with {@code typeName} + * @param factory The factory to associate with {@code typeName} */ public void put(String typeName, PrefabValueFactory factory) { if (typeName != null) { @@ -42,10 +43,10 @@ public void put(String typeName, PrefabValueFactory factory) { /** * Retrieves the factory from the cache for the given type. * - *

What happens when there is no factory, is undefined. Always call {@link #contains(Class)} - * first. + *

+ * What happens when there is no factory, is undefined. Always call {@link #contains(Class)} first. * - * @param The returned factory will have this as generic type. + * @param The returned factory will have this as generic type. * @param type The type for which a factory is needed. * @return A factory for the given type, or {@code null} if none is available. */ @@ -77,8 +78,8 @@ public FactoryCache copy() { } /** - * Returns a new {@code FactoryCache} instance containing the factories from {@code this} and - * from the {@code other} cache. + * Returns a new {@code FactoryCache} instance containing the factories from {@code this} and from the {@code other} + * cache. * * @param other The other cache * @return a new instance containing factories from {@code this} and {@code other} diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/PrefabValuesApi.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/PrefabValuesApi.java index 7d153fe08..b4e82f7ff 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/PrefabValuesApi.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/PrefabValuesApi.java @@ -17,21 +17,22 @@ public final class PrefabValuesApi { private PrefabValuesApi() {} public static void addPrefabValues( - FactoryCache factoryCache, - Objenesis objenesis, - Class otherType, - T red, - T blue - ) { + FactoryCache factoryCache, + Objenesis objenesis, + Class otherType, + T red, + T blue) { Validations.validateRedAndBluePrefabValues(otherType, red, blue); if (red.getClass().isArray()) { factoryCache.put(otherType, values(red, blue, red)); - } else { + } + else { try { T redCopy = ObjectAccessor.of(red).copy(objenesis); factoryCache.put(otherType, values(red, blue, redCopy)); - } catch (RuntimeException ignored) { + } + catch (RuntimeException ignored) { /* specifically, on Java 9+: InacessibleObjectException */ factoryCache.put(otherType, values(red, blue, red)); } @@ -40,53 +41,48 @@ public static void addPrefabValues( @SuppressWarnings("unchecked") public static void addPrefabValuesForField( - FieldCache fieldCache, - Objenesis objenesis, - Class type, - String fieldName, - T red, - T blue - ) { + FieldCache fieldCache, + Objenesis objenesis, + Class type, + String fieldName, + T red, + T blue) { Validations.validateRedAndBluePrefabValues((Class) red.getClass(), red, blue); Validations.validateFieldTypeMatches(type, fieldName, red.getClass()); if (red.getClass().isArray()) { fieldCache.put(fieldName, new Tuple<>(red, blue, red)); - } else { + } + else { try { T redCopy = ObjectAccessor.of(red).copy(objenesis); fieldCache.put(fieldName, new Tuple<>(red, blue, redCopy)); - } catch (RuntimeException ignored) { + } + catch (RuntimeException ignored) { /* specifically, on Java 9+: InacessibleObjectException */ fieldCache.put(fieldName, new Tuple<>(red, blue, red)); } } } - public static void addGenericPrefabValues( - FactoryCache factoryCache, - Class otherType, - Func1 factory - ) { + public static void addGenericPrefabValues(FactoryCache factoryCache, Class otherType, Func1 factory) { Validations.validateNotNull(factory, "factory is null."); addGenericPrefabValueFactory(factoryCache, otherType, simple(factory, null), 1); } public static void addGenericPrefabValues( - FactoryCache factoryCache, - Class otherType, - Func2 factory - ) { + FactoryCache factoryCache, + Class otherType, + Func2 factory) { Validations.validateNotNull(factory, "factory is null."); addGenericPrefabValueFactory(factoryCache, otherType, simple(factory, null), 2); } private static void addGenericPrefabValueFactory( - FactoryCache factoryCache, - Class otherType, - PrefabValueFactory factory, - int arity - ) { + FactoryCache factoryCache, + Class otherType, + PrefabValueFactory factory, + int arity) { Validations.validateGenericPrefabValues(otherType, factory, arity); factoryCache.put(otherType, factory); } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/VintageValueProvider.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/VintageValueProvider.java index 333b2ef6c..26d89e913 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/VintageValueProvider.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/VintageValueProvider.java @@ -1,6 +1,7 @@ package nl.jqno.equalsverifier.internal.instantiation.vintage; import java.util.*; + import nl.jqno.equalsverifier.internal.SuppressFBWarnings; import nl.jqno.equalsverifier.internal.exceptions.RecursionException; import nl.jqno.equalsverifier.internal.exceptions.ReflectionException; @@ -16,9 +17,8 @@ /** * Creator of prefabricated instances of classes, using a "vintage" strategy for doing so. * - * Vintage in this case means that it employs the creation strategy that EqualsVerifier has been - * using since its inception. This strategy is quite hacky and messy, and other strategies might - * be preferable. + * Vintage in this case means that it employs the creation strategy that EqualsVerifier has been using since its + * inception. This strategy is quite hacky and messy, and other strategies might be preferable. */ public class VintageValueProvider implements ValueProvider { @@ -32,7 +32,7 @@ public class VintageValueProvider implements ValueProvider { * Constructor. * * @param factoryCache The factories that can be used to create values. - * @param objenesis To instantiate non-record classes. + * @param objenesis To instantiate non-record classes. */ @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "A cache is inherently mutable.") public VintageValueProvider(FactoryCache factoryCache, Objenesis objenesis) { @@ -49,7 +49,8 @@ public Optional> provide(TypeTag tag) { /** * Returns the "red" prefabricated value of the specified type. * - *

It's always a different value from the "blue" one. + *

+ * It's always a different value from the "blue" one. * * @param The return value is cast to this type. * @param tag A description of the desired type, including generic parameters. @@ -62,7 +63,8 @@ public T giveRed(TypeTag tag) { /** * Returns the "blue" prefabricated value of the specified type. * - *

It's always a different value from the "red" one. + *

+ * It's always a different value from the "red" one. * * @param The return value is cast to this type. * @param tag A description of the desired type, including generic parameters. @@ -75,7 +77,8 @@ public T giveBlue(TypeTag tag) { /** * Returns a shallow copy of the "red" prefabricated value of the specified type. * - *

When possible, it's equal to but not the same as the "red" object. + *

+ * When possible, it's equal to but not the same as the "red" object. * * @param The return value is cast to this type. * @param tag A description of the desired type, including generic parameters. @@ -86,23 +89,18 @@ public T giveRedCopy(TypeTag tag) { } /** - * Returns a prefabricated value of the specified type, that is different from the specified - * value. + * Returns a prefabricated value of the specified type, that is different from the specified value. * - * @param The type of the value. - * @param tag A description of the desired type, including generic parameters. - * @param value A value that is different from the value that will be returned. + * @param The type of the value. + * @param tag A description of the desired type, including generic parameters. + * @param value A value that is different from the value that will be returned. * @param typeStack Keeps track of recursion in the type. * @return A value that is different from {@code value}. */ // CHECKSTYLE OFF: CyclomaticComplexity public T giveOther(TypeTag tag, T value, LinkedHashSet typeStack) { Class type = tag.getType(); - if ( - value != null && - !type.isAssignableFrom(value.getClass()) && - !wraps(type, value.getClass()) - ) { + if (value != null && !type.isAssignableFrom(value.getClass()) && !wraps(type, value.getClass())) { throw new ReflectionException("TypeTag does not match value."); } @@ -119,7 +117,8 @@ public T giveOther(TypeTag tag, T value, LinkedHashSet typeStack) { if (tuple.getRed().equals(value)) { return tuple.getBlue(); } - } catch (AbstractMethodError e) { + } + catch (AbstractMethodError e) { return tuple.getRed(); } } @@ -138,11 +137,10 @@ private boolean arraysAreDeeplyEqual(Object x, Object y) { } /** - * Makes sure that values for the specified type are present in the cache, but doesn't return - * them. + * Makes sure that values for the specified type are present in the cache, but doesn't return them. * - * @param The desired type. - * @param tag A description of the desired type, including generic parameters. + * @param The desired type. + * @param tag A description of the desired type, including generic parameters. * @param typeStack Keeps track of recursion in the type. */ public void realizeCacheFor(TypeTag tag, LinkedHashSet typeStack) { diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/AbstractGenericFactory.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/AbstractGenericFactory.java index 1534761a2..303a0349c 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/AbstractGenericFactory.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/AbstractGenericFactory.java @@ -5,14 +5,14 @@ import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; + import nl.jqno.equalsverifier.internal.SuppressFBWarnings; import nl.jqno.equalsverifier.internal.exceptions.ReflectionException; import nl.jqno.equalsverifier.internal.instantiation.vintage.VintageValueProvider; import nl.jqno.equalsverifier.internal.reflection.TypeTag; /** - * Abstract implementation of {@link PrefabValueFactory} that provides helper functions for dealing - * with generics. + * Abstract implementation of {@link PrefabValueFactory} that provides helper functions for dealing with generics. */ public abstract class AbstractGenericFactory implements PrefabValueFactory { @@ -34,21 +34,19 @@ protected TypeTag copyGenericTypesInto(Class type, TypeTag source) { } protected TypeTag determineAndCacheActualTypeTag( - int n, - TypeTag tag, - VintageValueProvider valueProvider, - LinkedHashSet typeStack - ) { + int n, + TypeTag tag, + VintageValueProvider valueProvider, + LinkedHashSet typeStack) { return determineAndCacheActualTypeTag(n, tag, valueProvider, typeStack, null); } protected TypeTag determineAndCacheActualTypeTag( - int n, - TypeTag tag, - VintageValueProvider valueProvider, - LinkedHashSet typeStack, - Class bottomType - ) { + int n, + TypeTag tag, + VintageValueProvider valueProvider, + LinkedHashSet typeStack, + Class bottomType) { TypeTag result = determineActualTypeTagFor(n, tag); if (bottomType != null && result.getType().equals(Object.class)) { result = new TypeTag(bottomType); @@ -66,24 +64,16 @@ protected TypeTag determineActualTypeTagFor(int n, TypeTag typeTag) { return genericTypes.get(n); } - @SuppressFBWarnings( - value = "DP_DO_INSIDE_DO_PRIVILEGED", - justification = "EV is run only from within unit tests" - ) - protected void invoke( - Class type, - Object receiver, - String methodName, - Class[] classes, - Object[] values - ) { + @SuppressFBWarnings(value = "DP_DO_INSIDE_DO_PRIVILEGED", justification = "EV is run only from within unit tests") + protected void invoke(Class type, Object receiver, String methodName, Class[] classes, Object[] values) { try { Method method = type.getMethod(methodName, classes); // Not necessary in the common case, but required for // https://bugs.java.com/view_bug.do?bug_id=6924232. method.setAccessible(true); method.invoke(receiver, values); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + } + catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw new ReflectionException(e); } } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/CopyFactory.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/CopyFactory.java index 332c159c2..385d62b5e 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/CopyFactory.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/CopyFactory.java @@ -2,6 +2,7 @@ import java.util.LinkedHashSet; import java.util.function.Function; + import nl.jqno.equalsverifier.internal.instantiation.vintage.VintageValueProvider; import nl.jqno.equalsverifier.internal.reflection.Tuple; import nl.jqno.equalsverifier.internal.reflection.TypeTag; @@ -17,11 +18,7 @@ public CopyFactory(Class source, Function copy) { } @Override - public Tuple createValues( - TypeTag tag, - VintageValueProvider valueProvider, - LinkedHashSet typeStack - ) { + public Tuple createValues(TypeTag tag, VintageValueProvider valueProvider, LinkedHashSet typeStack) { LinkedHashSet clone = cloneWith(typeStack, tag); TypeTag sourceTag = copyGenericTypesInto(source, tag); valueProvider.realizeCacheFor(sourceTag, clone); diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/EnumMapFactory.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/EnumMapFactory.java index 8ca507f7f..c1efbaec6 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/EnumMapFactory.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/EnumMapFactory.java @@ -4,6 +4,7 @@ import java.util.LinkedHashSet; import java.util.Map; import java.util.function.Function; + import nl.jqno.equalsverifier.internal.instantiation.vintage.VintageValueProvider; import nl.jqno.equalsverifier.internal.reflection.Tuple; import nl.jqno.equalsverifier.internal.reflection.TypeTag; @@ -18,11 +19,7 @@ public EnumMapFactory(Function factory) { } @Override - public Tuple createValues( - TypeTag tag, - VintageValueProvider valueProvider, - LinkedHashSet typeStack - ) { + public Tuple createValues(TypeTag tag, VintageValueProvider valueProvider, LinkedHashSet typeStack) { LinkedHashSet clone = cloneWith(typeStack, tag); TypeTag keyTag = determineAndCacheActualTypeTag(0, tag, valueProvider, clone, Enum.class); TypeTag valueTag = determineAndCacheActualTypeTag(1, tag, valueProvider, clone, Enum.class); diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/EnumSetFactory.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/EnumSetFactory.java index ad0c9a806..d7d5cfe8c 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/EnumSetFactory.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/EnumSetFactory.java @@ -4,13 +4,14 @@ import java.util.HashSet; import java.util.LinkedHashSet; import java.util.function.Function; + import nl.jqno.equalsverifier.internal.instantiation.vintage.VintageValueProvider; import nl.jqno.equalsverifier.internal.reflection.Tuple; import nl.jqno.equalsverifier.internal.reflection.TypeTag; /** - * Implementation of {@link PrefabValueFactory} that instantiates EnumSets using reflection, while - * taking generics into account. + * Implementation of {@link PrefabValueFactory} that instantiates EnumSets using reflection, while taking generics into + * account. */ @SuppressWarnings({ "unchecked", "rawtypes" }) public class EnumSetFactory extends AbstractGenericFactory { @@ -22,11 +23,7 @@ public EnumSetFactory(Function factory) { } @Override - public Tuple createValues( - TypeTag tag, - VintageValueProvider valueProvider, - LinkedHashSet typeStack - ) { + public Tuple createValues(TypeTag tag, VintageValueProvider valueProvider, LinkedHashSet typeStack) { LinkedHashSet clone = cloneWith(typeStack, tag); TypeTag entryTag = determineAndCacheActualTypeTag(0, tag, valueProvider, clone, Enum.class); diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/ExternalFactory.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/ExternalFactory.java index 7ed1166df..d98129299 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/ExternalFactory.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/ExternalFactory.java @@ -4,6 +4,7 @@ import static nl.jqno.equalsverifier.internal.reflection.Util.objects; import java.util.LinkedHashSet; + import nl.jqno.equalsverifier.internal.instantiation.vintage.FactoryCache; import nl.jqno.equalsverifier.internal.instantiation.vintage.VintageValueProvider; import nl.jqno.equalsverifier.internal.instantiation.vintage.prefabvalues.factoryproviders.FactoryProvider; @@ -14,7 +15,7 @@ public class ExternalFactory implements PrefabValueFactory { private static final String EXTERNAL_FACTORIES_PACKAGE = - "nl.jqno.equalsverifier.internal.instantiation.vintage.prefabvalues.factoryproviders."; + "nl.jqno.equalsverifier.internal.instantiation.vintage.prefabvalues.factoryproviders."; private final String factoryName; private FactoryCache factoryCache; @@ -24,11 +25,7 @@ public ExternalFactory(String factoryName) { } @Override - public Tuple createValues( - TypeTag tag, - VintageValueProvider valueProvider, - LinkedHashSet typeStack - ) { + public Tuple createValues(TypeTag tag, VintageValueProvider valueProvider, LinkedHashSet typeStack) { if (factoryCache == null) { ConditionalInstantiator ci = new ConditionalInstantiator(factoryName); FactoryProvider provider = ci.instantiate(classes(), objects()); diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/Factories.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/Factories.java index f2240b56f..b700bd88f 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/Factories.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/Factories.java @@ -4,6 +4,7 @@ import java.util.Map; import java.util.function.Function; import java.util.function.Supplier; + import nl.jqno.equalsverifier.Func.Func1; import nl.jqno.equalsverifier.Func.Func2; @@ -17,23 +18,15 @@ public static PrefabValueFactory values(T red, T blue, T redCopy) { return new SimpleFactory<>(red, blue, redCopy); } - public static PrefabValueFactory simple( - Func1 factory, - Supplier emptyFactory - ) { + public static PrefabValueFactory simple(Func1 factory, Supplier emptyFactory) { return new SimpleGenericFactory<>(factory, emptyFactory); } - public static PrefabValueFactory simple( - Func2 factory, - Supplier emptyFactory - ) { + public static PrefabValueFactory simple(Func2 factory, Supplier emptyFactory) { return new SimpleGenericFactory<>(factory, emptyFactory); } - public static > PrefabValueFactory collection( - Supplier emptyFactory - ) { + public static > PrefabValueFactory collection(Supplier emptyFactory) { Func1 f = a -> { T coll = emptyFactory.get(); coll.add(a); diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/FallbackFactory.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/FallbackFactory.java index 73f459a67..d21dcd431 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/FallbackFactory.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/FallbackFactory.java @@ -2,6 +2,7 @@ import java.lang.reflect.Array; import java.util.LinkedHashSet; + import nl.jqno.equalsverifier.internal.instantiation.vintage.VintageValueProvider; import nl.jqno.equalsverifier.internal.instantiation.vintage.reflection.ClassAccessor; import nl.jqno.equalsverifier.internal.reflection.Tuple; @@ -11,8 +12,9 @@ /** * Implementation of {@link PrefabValueFactory} that instantiates types "by force". * - *

It instantiates the type using bytecode magic, bypassing the constructor. Then it uses {@link - * VintageValueProvider} to fill up all the fields, recursively. + *

+ * It instantiates the type using bytecode magic, bypassing the constructor. Then it uses {@link VintageValueProvider} + * to fill up all the fields, recursively. */ public class FallbackFactory implements PrefabValueFactory { @@ -23,11 +25,7 @@ public FallbackFactory(Objenesis objenesis) { } @Override - public Tuple createValues( - TypeTag tag, - VintageValueProvider valueProvider, - LinkedHashSet typeStack - ) { + public Tuple createValues(TypeTag tag, VintageValueProvider valueProvider, LinkedHashSet typeStack) { @SuppressWarnings("unchecked") LinkedHashSet clone = (LinkedHashSet) typeStack.clone(); clone.add(tag); @@ -48,21 +46,20 @@ private Tuple giveEnumInstances(TypeTag tag) { T[] enumConstants = type.getEnumConstants(); switch (enumConstants.length) { - case 0: - return new Tuple<>(null, null, null); - case 1: - return new Tuple<>(enumConstants[0], enumConstants[0], enumConstants[0]); - default: - return new Tuple<>(enumConstants[0], enumConstants[1], enumConstants[0]); + case 0: + return new Tuple<>(null, null, null); + case 1: + return new Tuple<>(enumConstants[0], enumConstants[0], enumConstants[0]); + default: + return new Tuple<>(enumConstants[0], enumConstants[1], enumConstants[0]); } } @SuppressWarnings("unchecked") private Tuple giveArrayInstances( - TypeTag tag, - VintageValueProvider valueProvider, - LinkedHashSet typeStack - ) { + TypeTag tag, + VintageValueProvider valueProvider, + LinkedHashSet typeStack) { Class type = tag.getType(); Class componentType = type.getComponentType(); TypeTag componentTag = new TypeTag(componentType); @@ -78,11 +75,7 @@ private Tuple giveArrayInstances( return new Tuple<>(red, blue, redCopy); } - private Tuple giveInstances( - TypeTag tag, - VintageValueProvider valueProvider, - LinkedHashSet typeStack - ) { + private Tuple giveInstances(TypeTag tag, VintageValueProvider valueProvider, LinkedHashSet typeStack) { ClassAccessor accessor = ClassAccessor.of(tag.getType(), valueProvider, objenesis); T red = accessor.getRedObject(tag, typeStack); T blue = accessor.getBlueObject(tag, typeStack); diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/MapFactory.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/MapFactory.java index b50ca8a05..8880149b6 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/MapFactory.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/MapFactory.java @@ -3,13 +3,14 @@ import java.util.LinkedHashSet; import java.util.Map; import java.util.function.Supplier; + import nl.jqno.equalsverifier.internal.instantiation.vintage.VintageValueProvider; import nl.jqno.equalsverifier.internal.reflection.Tuple; import nl.jqno.equalsverifier.internal.reflection.TypeTag; /** - * Implementation of {@link PrefabValueFactory} that specializes in creating implementations of - * {@link Map}, taking generics into account. + * Implementation of {@link PrefabValueFactory} that specializes in creating implementations of {@link Map}, taking + * generics into account. */ @SuppressWarnings({ "rawtypes", "unchecked" }) public class MapFactory extends AbstractGenericFactory { @@ -21,11 +22,7 @@ public MapFactory(Supplier createEmpty) { } @Override - public Tuple createValues( - TypeTag tag, - VintageValueProvider valueProvider, - LinkedHashSet typeStack - ) { + public Tuple createValues(TypeTag tag, VintageValueProvider valueProvider, LinkedHashSet typeStack) { LinkedHashSet clone = cloneWith(typeStack, tag); TypeTag keyTag = determineAndCacheActualTypeTag(0, tag, valueProvider, clone); TypeTag valueTag = determineAndCacheActualTypeTag(1, tag, valueProvider, clone); diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/PrefabValueFactory.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/PrefabValueFactory.java index c7f03252a..23aa478f2 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/PrefabValueFactory.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/PrefabValueFactory.java @@ -1,6 +1,7 @@ package nl.jqno.equalsverifier.internal.instantiation.vintage.prefabvalues.factories; import java.util.LinkedHashSet; + import nl.jqno.equalsverifier.internal.instantiation.vintage.VintageValueProvider; import nl.jqno.equalsverifier.internal.reflection.Tuple; import nl.jqno.equalsverifier.internal.reflection.TypeTag; @@ -15,15 +16,11 @@ public interface PrefabValueFactory { /** * Creates a tuple of two prefab values. * - * @param tag The typetag of the type for which to create values. + * @param tag The typetag of the type for which to create values. * @param valueProvider Repository for querying instances of generic types of the type tag. - * @param typeStack A stack of {@link TypeTag}s that require tag in order to be created. Used - * for recursion detection. + * @param typeStack A stack of {@link TypeTag}s that require tag in order to be created. Used for recursion + * detection. * @return A "red" instance of {@code T}. */ - Tuple createValues( - TypeTag tag, - VintageValueProvider valueProvider, - LinkedHashSet typeStack - ); + Tuple createValues(TypeTag tag, VintageValueProvider valueProvider, LinkedHashSet typeStack); } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/SimpleFactory.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/SimpleFactory.java index 77375f3d6..f405b97d9 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/SimpleFactory.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/SimpleFactory.java @@ -1,13 +1,13 @@ package nl.jqno.equalsverifier.internal.instantiation.vintage.prefabvalues.factories; import java.util.LinkedHashSet; + import nl.jqno.equalsverifier.internal.instantiation.vintage.VintageValueProvider; import nl.jqno.equalsverifier.internal.reflection.Tuple; import nl.jqno.equalsverifier.internal.reflection.TypeTag; /** - * Implementation of {@link PrefabValueFactory} that holds on to two instances that have already - * been created. + * Implementation of {@link PrefabValueFactory} that holds on to two instances that have already been created. */ public class SimpleFactory implements PrefabValueFactory { @@ -18,11 +18,7 @@ public SimpleFactory(T red, T blue, T redCopy) { } @Override - public Tuple createValues( - TypeTag tag, - VintageValueProvider valueProvider, - LinkedHashSet typeStack - ) { + public Tuple createValues(TypeTag tag, VintageValueProvider valueProvider, LinkedHashSet typeStack) { return tuple; } } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/SimpleGenericFactory.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/SimpleGenericFactory.java index 70a8b683d..3c2fc1b3e 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/SimpleGenericFactory.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/SimpleGenericFactory.java @@ -4,6 +4,7 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.function.Supplier; + import nl.jqno.equalsverifier.Func; import nl.jqno.equalsverifier.internal.instantiation.vintage.VintageValueProvider; import nl.jqno.equalsverifier.internal.reflection.Tuple; @@ -20,11 +21,7 @@ public SimpleGenericFactory(Func factory, Supplier emptyFactory) { } @Override - public Tuple createValues( - TypeTag tag, - VintageValueProvider valueProvider, - LinkedHashSet typeStack - ) { + public Tuple createValues(TypeTag tag, VintageValueProvider valueProvider, LinkedHashSet typeStack) { LinkedHashSet clone = cloneWith(typeStack, tag); List redValues = new ArrayList<>(); @@ -45,9 +42,7 @@ public Tuple createValues( } Object red = factory.apply(redValues); - Object blue = useEmpty && emptyFactory != null - ? emptyFactory.get() - : factory.apply(blueValues); + Object blue = useEmpty && emptyFactory != null ? emptyFactory.get() : factory.apply(blueValues); Object redCopy = factory.apply(redValues); return Tuple.of(red, blue, redCopy); diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factoryproviders/AwtFactoryProvider.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factoryproviders/AwtFactoryProvider.java index ccee73a6b..898f43940 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factoryproviders/AwtFactoryProvider.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factoryproviders/AwtFactoryProvider.java @@ -9,6 +9,7 @@ import java.awt.color.ICC_ColorSpace; import java.awt.color.ICC_Profile; import java.awt.image.BufferedImage; + import nl.jqno.equalsverifier.internal.instantiation.vintage.FactoryCache; public final class AwtFactoryProvider implements FactoryProvider { @@ -20,38 +21,34 @@ public FactoryCache getFactoryCache() { FactoryCache cache = new FactoryCache(); cache.put(Color.class, values(Color.RED, Color.BLUE, Color.RED)); - cache.put( - ColorSpace.class, - values( - ColorSpace.getInstance(CS_RED), - ColorSpace.getInstance(CS_BLUE), - ColorSpace.getInstance(CS_RED) - ) - ); - cache.put( - ICC_ColorSpace.class, - values( - ICC_ColorSpace.getInstance(CS_RED), - ICC_ColorSpace.getInstance(CS_BLUE), - ICC_ColorSpace.getInstance(CS_RED) - ) - ); - cache.put( - ICC_Profile.class, - values( - ICC_Profile.getInstance(CS_RED), - ICC_Profile.getInstance(CS_BLUE), - ICC_Profile.getInstance(CS_RED) - ) - ); - cache.put( - Font.class, - values( - new Font(Font.SERIF, Font.PLAIN, 10), - new Font(Font.SANS_SERIF, Font.PLAIN, 12), - new Font(Font.SERIF, Font.PLAIN, 10) - ) - ); + cache + .put( + ColorSpace.class, + values( + ColorSpace.getInstance(CS_RED), + ColorSpace.getInstance(CS_BLUE), + ColorSpace.getInstance(CS_RED))); + cache + .put( + ICC_ColorSpace.class, + values( + ICC_ColorSpace.getInstance(CS_RED), + ICC_ColorSpace.getInstance(CS_BLUE), + ICC_ColorSpace.getInstance(CS_RED))); + cache + .put( + ICC_Profile.class, + values( + ICC_Profile.getInstance(CS_RED), + ICC_Profile.getInstance(CS_BLUE), + ICC_Profile.getInstance(CS_RED))); + cache + .put( + Font.class, + values( + new Font(Font.SERIF, Font.PLAIN, 10), + new Font(Font.SANS_SERIF, Font.PLAIN, 12), + new Font(Font.SERIF, Font.PLAIN, 10))); Image red = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB); Image blue = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB); cache.put(Image.class, values(red, blue, red)); diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factoryproviders/GuavaFactoryProvider.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factoryproviders/GuavaFactoryProvider.java index ebba614d2..40867acbd 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factoryproviders/GuavaFactoryProvider.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factoryproviders/GuavaFactoryProvider.java @@ -2,10 +2,11 @@ import static nl.jqno.equalsverifier.internal.instantiation.vintage.prefabvalues.factories.Factories.*; -import com.google.common.collect.*; -import com.google.common.reflect.TypeToken; import java.util.*; import java.util.function.Supplier; + +import com.google.common.collect.*; +import com.google.common.reflect.TypeToken; import nl.jqno.equalsverifier.internal.instantiation.vintage.FactoryCache; import nl.jqno.equalsverifier.internal.instantiation.vintage.VintageValueProvider; import nl.jqno.equalsverifier.internal.instantiation.vintage.prefabvalues.factories.*; @@ -14,9 +15,7 @@ public final class GuavaFactoryProvider implements FactoryProvider { - private static final Comparator OBJECT_COMPARATOR = Comparator.comparingInt( - Object::hashCode - ); + private static final Comparator OBJECT_COMPARATOR = Comparator.comparingInt(Object::hashCode); public FactoryCache getFactoryCache() { FactoryCache cache = new FactoryCache(); @@ -42,10 +41,7 @@ private void putMultisets(FactoryCache cache) { cache.put(ConcurrentHashMultiset.class, collection(ConcurrentHashMultiset::create)); cache.put(EnumMultiset.class, new EnumSetFactory<>(c -> EnumMultiset.create(c))); cache.put(ImmutableMultiset.class, copy(Set.class, ImmutableMultiset::copyOf)); - cache.put( - ImmutableSortedMultiset.class, - copy(SortedMultiset.class, ImmutableSortedMultiset::copyOfSorted) - ); + cache.put(ImmutableSortedMultiset.class, copy(SortedMultiset.class, ImmutableSortedMultiset::copyOfSorted)); } @SuppressWarnings("unchecked") @@ -53,18 +49,12 @@ private void putMultimaps(FactoryCache cache) { cache.put(Multimap.class, multimap(ArrayListMultimap::create)); cache.put(ListMultimap.class, multimap(ArrayListMultimap::create)); cache.put(SetMultimap.class, multimap(HashMultimap::create)); - cache.put( - SortedSetMultimap.class, - multimap(() -> TreeMultimap.create(OBJECT_COMPARATOR, OBJECT_COMPARATOR)) - ); + cache.put(SortedSetMultimap.class, multimap(() -> TreeMultimap.create(OBJECT_COMPARATOR, OBJECT_COMPARATOR))); cache.put(ArrayListMultimap.class, multimap(ArrayListMultimap::create)); cache.put(HashMultimap.class, multimap(HashMultimap::create)); cache.put(LinkedListMultimap.class, multimap(LinkedListMultimap::create)); cache.put(LinkedHashMultimap.class, multimap(LinkedHashMultimap::create)); - cache.put( - TreeMultimap.class, - multimap(() -> TreeMultimap.create(OBJECT_COMPARATOR, OBJECT_COMPARATOR)) - ); + cache.put(TreeMultimap.class, multimap(() -> TreeMultimap.create(OBJECT_COMPARATOR, OBJECT_COMPARATOR))); cache.put(ImmutableListMultimap.class, copy(Multimap.class, ImmutableListMultimap::copyOf)); cache.put(ImmutableSetMultimap.class, copy(Multimap.class, ImmutableSetMultimap::copyOf)); cache.put(ImmutableMultimap.class, copy(Multimap.class, ImmutableListMultimap::copyOf)); @@ -83,10 +73,7 @@ private void putBiMaps(FactoryCache cache) { private void putTables(FactoryCache cache) { cache.put(Table.class, table(HashBasedTable::create)); cache.put(HashBasedTable.class, table(HashBasedTable::create)); - cache.put( - TreeBasedTable.class, - table(() -> TreeBasedTable.create(OBJECT_COMPARATOR, OBJECT_COMPARATOR)) - ); + cache.put(TreeBasedTable.class, table(() -> TreeBasedTable.create(OBJECT_COMPARATOR, OBJECT_COMPARATOR))); cache.put(ArrayTable.class, copy(Table.class, ArrayTable::create)); cache.put(ImmutableTable.class, copy(Table.class, ImmutableTable::copyOf)); } @@ -94,10 +81,10 @@ private void putTables(FactoryCache cache) { @SuppressWarnings("unchecked") private void putRegularCollections(FactoryCache cache) { cache.put(EvictingQueue.class, collection(() -> EvictingQueue.create(10))); - cache.put( - MinMaxPriorityQueue.class, - collection(() -> MinMaxPriorityQueue.orderedBy(OBJECT_COMPARATOR).create()) - ); + cache + .put( + MinMaxPriorityQueue.class, + collection(() -> MinMaxPriorityQueue.orderedBy(OBJECT_COMPARATOR).create())); cache.put(ImmutableRangeSet.class, copy(Range.class, ImmutableRangeSet::of)); cache.put(TreeRangeSet.class, copy(ImmutableRangeSet.class, TreeRangeSet::create)); cache.put(RangeSet.class, copy(ImmutableRangeSet.class, TreeRangeSet::create)); @@ -114,38 +101,26 @@ private void putImmutableClasses(FactoryCache cache) { } private void putNewTypes(FactoryCache cache) { - cache.put( - Range.class, - Factories., Range>simple(Range::atLeast, Range::all) - ); - cache.put( - com.google.common.base.Optional.class, - simple(com.google.common.base.Optional::of, com.google.common.base.Optional::absent) - ); - cache.put( - TypeToken.class, - values( - TypeToken.of(Object.class), - TypeToken.of(String.class), - TypeToken.of(Object.class) - ) - ); + cache.put(Range.class, Factories., Range>simple(Range::atLeast, Range::all)); + cache + .put( + com.google.common.base.Optional.class, + simple(com.google.common.base.Optional::of, com.google.common.base.Optional::absent)); + cache + .put( + TypeToken.class, + values(TypeToken.of(Object.class), TypeToken.of(String.class), TypeToken.of(Object.class))); } - private > MultimapFactory multimap( - Supplier factory - ) { + private > MultimapFactory multimap(Supplier factory) { return new MultimapFactory<>(factory); } - private > TableFactory table( - Supplier factory - ) { + private > TableFactory table(Supplier factory) { return new TableFactory<>(factory); } - private static final class MultimapFactory> - extends AbstractGenericFactory { + private static final class MultimapFactory> extends AbstractGenericFactory { private final Supplier factory; @@ -155,10 +130,9 @@ private MultimapFactory(Supplier factory) { @Override public Tuple createValues( - TypeTag tag, - VintageValueProvider valueProvider, - LinkedHashSet typeStack - ) { + TypeTag tag, + VintageValueProvider valueProvider, + LinkedHashSet typeStack) { LinkedHashSet clone = cloneWith(typeStack, tag); TypeTag keyTag = determineAndCacheActualTypeTag(0, tag, valueProvider, clone); TypeTag valueTag = determineAndCacheActualTypeTag(1, tag, valueProvider, clone); @@ -174,8 +148,7 @@ public Tuple createValues( } } - private static final class TableFactory> - extends AbstractGenericFactory { + private static final class TableFactory> extends AbstractGenericFactory { private final Supplier factory; @@ -185,10 +158,9 @@ private TableFactory(Supplier factory) { @Override public Tuple createValues( - TypeTag tag, - VintageValueProvider valueProvider, - LinkedHashSet typeStack - ) { + TypeTag tag, + VintageValueProvider valueProvider, + LinkedHashSet typeStack) { LinkedHashSet clone = cloneWith(typeStack, tag); TypeTag columnTag = determineAndCacheActualTypeTag(0, tag, valueProvider, clone); TypeTag rowTag = determineAndCacheActualTypeTag(1, tag, valueProvider, clone); @@ -197,21 +169,17 @@ public Tuple createValues( T red = factory.get(); T blue = factory.get(); T redCopy = factory.get(); - red.put( - valueProvider.giveRed(columnTag), - valueProvider.giveRed(rowTag), - valueProvider.giveBlue(valueTag) - ); - blue.put( - valueProvider.giveBlue(columnTag), - valueProvider.giveBlue(rowTag), - valueProvider.giveBlue(valueTag) - ); - redCopy.put( - valueProvider.giveRed(columnTag), - valueProvider.giveRed(rowTag), - valueProvider.giveBlue(valueTag) - ); + red.put(valueProvider.giveRed(columnTag), valueProvider.giveRed(rowTag), valueProvider.giveBlue(valueTag)); + blue + .put( + valueProvider.giveBlue(columnTag), + valueProvider.giveBlue(rowTag), + valueProvider.giveBlue(valueTag)); + redCopy + .put( + valueProvider.giveRed(columnTag), + valueProvider.giveRed(rowTag), + valueProvider.giveBlue(valueTag)); return Tuple.of(red, blue, redCopy); } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factoryproviders/JavaFxFactoryProvider.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factoryproviders/JavaFxFactoryProvider.java index b47636262..3daa9ba8e 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factoryproviders/JavaFxFactoryProvider.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factoryproviders/JavaFxFactoryProvider.java @@ -7,6 +7,7 @@ import java.util.*; import java.util.function.Function; + import nl.jqno.equalsverifier.internal.instantiation.vintage.FactoryCache; import nl.jqno.equalsverifier.internal.instantiation.vintage.VintageValueProvider; import nl.jqno.equalsverifier.internal.instantiation.vintage.prefabvalues.factories.AbstractGenericFactory; @@ -21,74 +22,34 @@ public final class JavaFxFactoryProvider implements FactoryProvider { private static final String JAVAFX_PROPERTY_PACKAGE = "javafx.beans.property."; /* - * As long as there's no easy dependency for JavaFX to rely on in Maven, - * we can't refer to the actual types, and have to go around it with String - * representations of the type names. + * As long as there's no easy dependency for JavaFX to rely on in Maven, we can't refer to the actual types, and + * have to go around it with String representations of the type names. */ public FactoryCache getFactoryCache() { FactoryCache cache = new FactoryCache(); - cache.put( - JAVAFX_COLLECTIONS_PACKAGE + "ObservableList", - fxCollection(List.class, "observableList") - ); - cache.put( - JAVAFX_COLLECTIONS_PACKAGE + "ObservableMap", - fxCollection(Map.class, "observableMap") - ); - cache.put( - JAVAFX_COLLECTIONS_PACKAGE + "ObservableSet", - fxCollection(Set.class, "observableSet") - ); - cache.put( - JAVAFX_PROPERTY_PACKAGE + "BooleanProperty", - fxProperty("SimpleBooleanProperty", boolean.class) - ); - cache.put( - JAVAFX_PROPERTY_PACKAGE + "DoubleProperty", - fxProperty("SimpleDoubleProperty", double.class) - ); - cache.put( - JAVAFX_PROPERTY_PACKAGE + "FloatProperty", - fxProperty("SimpleFloatProperty", float.class) - ); - cache.put( - JAVAFX_PROPERTY_PACKAGE + "IntegerProperty", - fxProperty("SimpleIntegerProperty", int.class) - ); - cache.put( - JAVAFX_PROPERTY_PACKAGE + "ListProperty", - fxProperty( - "SimpleListProperty", - classForName(JAVAFX_COLLECTIONS_PACKAGE + "ObservableList") - ) - ); - cache.put( - JAVAFX_PROPERTY_PACKAGE + "LongProperty", - fxProperty("SimpleLongProperty", long.class) - ); - cache.put( - JAVAFX_PROPERTY_PACKAGE + "MapProperty", - fxProperty( - "SimpleMapProperty", - classForName(JAVAFX_COLLECTIONS_PACKAGE + "ObservableMap") - ) - ); - cache.put( - JAVAFX_PROPERTY_PACKAGE + "ObjectProperty", - fxProperty("SimpleObjectProperty", Object.class) - ); - cache.put( - JAVAFX_PROPERTY_PACKAGE + "SetProperty", - fxProperty( - "SimpleSetProperty", - classForName(JAVAFX_COLLECTIONS_PACKAGE + "ObservableSet") - ) - ); - cache.put( - JAVAFX_PROPERTY_PACKAGE + "StringProperty", - fxProperty("SimpleStringProperty", String.class) - ); + cache.put(JAVAFX_COLLECTIONS_PACKAGE + "ObservableList", fxCollection(List.class, "observableList")); + cache.put(JAVAFX_COLLECTIONS_PACKAGE + "ObservableMap", fxCollection(Map.class, "observableMap")); + cache.put(JAVAFX_COLLECTIONS_PACKAGE + "ObservableSet", fxCollection(Set.class, "observableSet")); + cache.put(JAVAFX_PROPERTY_PACKAGE + "BooleanProperty", fxProperty("SimpleBooleanProperty", boolean.class)); + cache.put(JAVAFX_PROPERTY_PACKAGE + "DoubleProperty", fxProperty("SimpleDoubleProperty", double.class)); + cache.put(JAVAFX_PROPERTY_PACKAGE + "FloatProperty", fxProperty("SimpleFloatProperty", float.class)); + cache.put(JAVAFX_PROPERTY_PACKAGE + "IntegerProperty", fxProperty("SimpleIntegerProperty", int.class)); + cache + .put( + JAVAFX_PROPERTY_PACKAGE + "ListProperty", + fxProperty("SimpleListProperty", classForName(JAVAFX_COLLECTIONS_PACKAGE + "ObservableList"))); + cache.put(JAVAFX_PROPERTY_PACKAGE + "LongProperty", fxProperty("SimpleLongProperty", long.class)); + cache + .put( + JAVAFX_PROPERTY_PACKAGE + "MapProperty", + fxProperty("SimpleMapProperty", classForName(JAVAFX_COLLECTIONS_PACKAGE + "ObservableMap"))); + cache.put(JAVAFX_PROPERTY_PACKAGE + "ObjectProperty", fxProperty("SimpleObjectProperty", Object.class)); + cache + .put( + JAVAFX_PROPERTY_PACKAGE + "SetProperty", + fxProperty("SimpleSetProperty", classForName(JAVAFX_COLLECTIONS_PACKAGE + "ObservableSet"))); + cache.put(JAVAFX_PROPERTY_PACKAGE + "StringProperty", fxProperty("SimpleStringProperty", String.class)); return cache; } @@ -109,36 +70,22 @@ static final class PropertyFactory extends AbstractGenericFactory { @Override public Tuple createValues( - TypeTag tag, - VintageValueProvider valueProvider, - LinkedHashSet typeStack - ) { + TypeTag tag, + VintageValueProvider valueProvider, + LinkedHashSet typeStack) { ConditionalInstantiator ci = new ConditionalInstantiator(fullyQualifiedTypeName); TypeTag singleParameterTag = copyGenericTypesInto(parameterRawType, tag); - T red = ci.instantiate( - classes(parameterRawType), - objects(valueProvider.giveRed(singleParameterTag)) - ); - T blue = ci.instantiate( - classes(parameterRawType), - objects(valueProvider.giveBlue(singleParameterTag)) - ); - T redCopy = ci.instantiate( - classes(parameterRawType), - objects(valueProvider.giveRed(singleParameterTag)) - ); + T red = ci.instantiate(classes(parameterRawType), objects(valueProvider.giveRed(singleParameterTag))); + T blue = ci.instantiate(classes(parameterRawType), objects(valueProvider.giveBlue(singleParameterTag))); + T redCopy = ci.instantiate(classes(parameterRawType), objects(valueProvider.giveRed(singleParameterTag))); return Tuple.of(red, blue, redCopy); } } - private static PrefabValueFactory fxCollection( - Class source, - String copyMethodName - ) { - Function f = a -> - new ConditionalInstantiator(JAVAFX_COLLECTIONS_PACKAGE + "FXCollections") + private static PrefabValueFactory fxCollection(Class source, String copyMethodName) { + Function f = a -> new ConditionalInstantiator(JAVAFX_COLLECTIONS_PACKAGE + "FXCollections") .callFactory(copyMethodName, classes(source), objects(a)); return copy(source, f); } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factoryproviders/JavaxFactoryProvider.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factoryproviders/JavaxFactoryProvider.java index a223b962f..8be1c35ba 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factoryproviders/JavaxFactoryProvider.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factoryproviders/JavaxFactoryProvider.java @@ -4,6 +4,7 @@ import javax.naming.Reference; import javax.swing.tree.DefaultMutableTreeNode; + import nl.jqno.equalsverifier.internal.instantiation.vintage.FactoryCache; public final class JavaxFactoryProvider implements FactoryProvider { @@ -11,18 +12,14 @@ public final class JavaxFactoryProvider implements FactoryProvider { public FactoryCache getFactoryCache() { FactoryCache cache = new FactoryCache(); - cache.put( - Reference.class, - values(new Reference("one"), new Reference("two"), new Reference("one")) - ); - cache.put( - DefaultMutableTreeNode.class, - values( - new DefaultMutableTreeNode(), - new DefaultMutableTreeNode(new Object()), - new DefaultMutableTreeNode() - ) - ); + cache.put(Reference.class, values(new Reference("one"), new Reference("two"), new Reference("one"))); + cache + .put( + DefaultMutableTreeNode.class, + values( + new DefaultMutableTreeNode(), + new DefaultMutableTreeNode(new Object()), + new DefaultMutableTreeNode())); return cache; } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factoryproviders/JodaFactoryProvider.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factoryproviders/JodaFactoryProvider.java index 255320318..fbc378e65 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factoryproviders/JodaFactoryProvider.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factoryproviders/JodaFactoryProvider.java @@ -12,34 +12,23 @@ public final class JodaFactoryProvider implements FactoryProvider { public FactoryCache getFactoryCache() { FactoryCache cache = new FactoryCache(); - cache.put( - Chronology.class, - values( - GregorianChronology.getInstanceUTC(), - ISOChronology.getInstanceUTC(), - GregorianChronology.getInstanceUTC() - ) - ); - cache.put( - DateTimeZone.class, - values( - DateTimeZone.forOffsetHours(+1), - DateTimeZone.forOffsetHours(-10), - DateTimeZone.forOffsetHours(+1) - ) - ); - cache.put( - PeriodType.class, - values(PeriodType.days(), PeriodType.hours(), PeriodType.days()) - ); - cache.put( - YearMonth.class, - values(new YearMonth(2018, 5), new YearMonth(2014, 7), new YearMonth(2018, 5)) - ); - cache.put( - MonthDay.class, - values(new MonthDay(6, 1), new MonthDay(6, 26), new MonthDay(6, 1)) - ); + cache + .put( + Chronology.class, + values( + GregorianChronology.getInstanceUTC(), + ISOChronology.getInstanceUTC(), + GregorianChronology.getInstanceUTC())); + cache + .put( + DateTimeZone.class, + values( + DateTimeZone.forOffsetHours(+1), + DateTimeZone.forOffsetHours(-10), + DateTimeZone.forOffsetHours(+1))); + cache.put(PeriodType.class, values(PeriodType.days(), PeriodType.hours(), PeriodType.days())); + cache.put(YearMonth.class, values(new YearMonth(2018, 5), new YearMonth(2014, 7), new YearMonth(2018, 5))); + cache.put(MonthDay.class, values(new MonthDay(6, 1), new MonthDay(6, 26), new MonthDay(6, 1))); return cache; } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factoryproviders/RmiFactoryProvider.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factoryproviders/RmiFactoryProvider.java index 5f55cac20..6779a6717 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factoryproviders/RmiFactoryProvider.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factoryproviders/RmiFactoryProvider.java @@ -4,6 +4,7 @@ import java.rmi.dgc.VMID; import java.rmi.server.UID; + import nl.jqno.equalsverifier.internal.instantiation.vintage.FactoryCache; public final class RmiFactoryProvider implements FactoryProvider { diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/ClassAccessor.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/ClassAccessor.java index 905184334..d5b266771 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/ClassAccessor.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/ClassAccessor.java @@ -1,15 +1,15 @@ package nl.jqno.equalsverifier.internal.instantiation.vintage.reflection; import java.util.LinkedHashSet; + import nl.jqno.equalsverifier.internal.instantiation.vintage.VintageValueProvider; import nl.jqno.equalsverifier.internal.reflection.Instantiator; import nl.jqno.equalsverifier.internal.reflection.TypeTag; import org.objenesis.Objenesis; /** - * Instantiates and populates objects of a given class. {@link ClassAccessor} can create two - * different instances of T, which are guaranteed not to be equal to each other, and which contain - * no null values. + * Instantiates and populates objects of a given class. {@link ClassAccessor} can create two different instances of T, + * which are guaranteed not to be equal to each other, and which contain no null values. * * @param A class. */ @@ -29,27 +29,23 @@ public class ClassAccessor { /** * Factory method. * - * @param The class on which {@link ClassAccessor} operates. - * @param type The class on which {@link ClassAccessor} operates. Should be the same as T. + * @param The class on which {@link ClassAccessor} operates. + * @param type The class on which {@link ClassAccessor} operates. Should be the same as T. * @param valueProvider Prefabricated values with which to fill instantiated objects. - * @param objenesis To instantiate non-record classes. + * @param objenesis To instantiate non-record classes. * @return A {@link ClassAccessor} for T. */ - public static ClassAccessor of( - Class type, - VintageValueProvider valueProvider, - Objenesis objenesis - ) { + public static ClassAccessor of(Class type, VintageValueProvider valueProvider, Objenesis objenesis) { return new ClassAccessor<>(type, valueProvider, objenesis); } /** - * Returns an instance of T that is not equal to the instance of T returned by {@link - * #getBlueObject(TypeTag, LinkedHashSet)}. + * Returns an instance of T that is not equal to the instance of T returned by + * {@link #getBlueObject(TypeTag, LinkedHashSet)}. * - * @param enclosingType Describes the type that contains this object as a field, to determine - * any generic parameters it may contain. - * @param typeStack Keeps track of recursion in the type. + * @param enclosingType Describes the type that contains this object as a field, to determine any generic parameters + * it may contain. + * @param typeStack Keeps track of recursion in the type. * @return An instance of T. */ public T getRedObject(TypeTag enclosingType, LinkedHashSet typeStack) { @@ -59,25 +55,22 @@ public T getRedObject(TypeTag enclosingType, LinkedHashSet typeStack) { /** * Returns an {@link ObjectAccessor} for {@link #getRedObject(TypeTag, LinkedHashSet)}. * - * @param enclosingType Describes the type that contains this object as a field, to determine - * any generic parameters it may contain. - * @param typeStack Keeps track of recursion in the type. + * @param enclosingType Describes the type that contains this object as a field, to determine any generic parameters + * it may contain. + * @param typeStack Keeps track of recursion in the type. * @return An {@link ObjectAccessor} for {@link #getRedObject}. */ - public ObjectAccessor getRedAccessor( - TypeTag enclosingType, - LinkedHashSet typeStack - ) { + public ObjectAccessor getRedAccessor(TypeTag enclosingType, LinkedHashSet typeStack) { return buildObjectAccessor().scramble(valueProvider, enclosingType, typeStack); } /** - * Returns an instance of T that is not equal to the instance of T returned by {@link - * #getRedObject(TypeTag, LinkedHashSet)}. + * Returns an instance of T that is not equal to the instance of T returned by + * {@link #getRedObject(TypeTag, LinkedHashSet)}. * - * @param enclosingType Describes the type that contains this object as a field, to determine - * any generic parameters it may contain. - * @param typeStack Keeps track of recursion in the type. + * @param enclosingType Describes the type that contains this object as a field, to determine any generic parameters + * it may contain. + * @param typeStack Keeps track of recursion in the type. * @return An instance of T. */ public T getBlueObject(TypeTag enclosingType, LinkedHashSet typeStack) { @@ -87,18 +80,15 @@ public T getBlueObject(TypeTag enclosingType, LinkedHashSet typeStack) /** * Returns an {@link ObjectAccessor} for {@link #getBlueObject(TypeTag, LinkedHashSet)}. * - * @param enclosingType Describes the type that contains this object as a field, to determine - * any generic parameters it may contain. - * @param typeStack Keeps track of recursion in the type. + * @param enclosingType Describes the type that contains this object as a field, to determine any generic parameters + * it may contain. + * @param typeStack Keeps track of recursion in the type. * @return An {@link ObjectAccessor} for {@link #getBlueObject(TypeTag, LinkedHashSet)}. */ - public ObjectAccessor getBlueAccessor( - TypeTag enclosingType, - LinkedHashSet typeStack - ) { + public ObjectAccessor getBlueAccessor(TypeTag enclosingType, LinkedHashSet typeStack) { return buildObjectAccessor() - .scramble(valueProvider, enclosingType, typeStack) - .scramble(valueProvider, enclosingType, typeStack); + .scramble(valueProvider, enclosingType, typeStack) + .scramble(valueProvider, enclosingType, typeStack); } private ObjectAccessor buildObjectAccessor() { diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/FieldModifier.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/FieldModifier.java index 546236fd3..8704db134 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/FieldModifier.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/FieldModifier.java @@ -4,6 +4,7 @@ import java.lang.reflect.Field; import java.util.LinkedHashSet; + import nl.jqno.equalsverifier.internal.exceptions.ReflectionException; import nl.jqno.equalsverifier.internal.instantiation.vintage.VintageValueProvider; import nl.jqno.equalsverifier.internal.reflection.FieldProbe; @@ -23,7 +24,7 @@ private FieldModifier(Field field, Object object) { /** * Factory method. * - * @param field The field to modify. + * @param field The field to modify. * @param object An object that contains the field we want to modify. * @return A {@link FieldModifier} for {@link field} in {@link object}. */ @@ -34,7 +35,8 @@ public static FieldModifier of(Field field, Object object) { /** * Copies field's value to the corresponding field in the specified object. * - *

Ignores static fields and fields that can't be modified reflectively. + *

+ * Ignores static fields and fields that can't be modified reflectively. * * @param to The object into which to copy the field. * @throws ReflectionException If the operation fails. @@ -44,23 +46,23 @@ public void copyTo(Object to) { } /** - * Changes the field's value to something else. The new value will never be null. Other than - * that, the precise value is undefined. + * Changes the field's value to something else. The new value will never be null. Other than that, the precise value + * is undefined. * - *

Ignores static fields and fields that can't be modified reflectively. + *

+ * Ignores static fields and fields that can't be modified reflectively. * - * @param valueProvider If the field is of a type contained within prefabValues, the new value - * will be taken from it. - * @param enclosingType A tag for the type that contains the field. Needed to determine a - * generic type, if it has one.. - * @param typeStack Keeps track of recursion in the type. + * @param valueProvider If the field is of a type contained within prefabValues, the new value will be taken from + * it. + * @param enclosingType A tag for the type that contains the field. Needed to determine a generic type, if it has + * one.. + * @param typeStack Keeps track of recursion in the type. * @throws ReflectionException If the operation fails. */ public void changeField( - VintageValueProvider valueProvider, - TypeTag enclosingType, - LinkedHashSet typeStack - ) { + VintageValueProvider valueProvider, + TypeTag enclosingType, + LinkedHashSet typeStack) { FieldChanger fm = () -> { TypeTag tag = TypeTag.of(field, enclosingType); Object newValue = valueProvider.giveOther(tag, field.get(object), typeStack); @@ -85,17 +87,16 @@ private void change(FieldChanger changer, boolean includeStatic) { private void wrappedChange(FieldChanger changer) throws IllegalAccessException { try { changer.change(); - } catch (IllegalArgumentException e) { + } + catch (IllegalArgumentException e) { String msg = e.getMessage(); if (msg.startsWith("Can not set") || msg.startsWith("Can not get")) { throw new ReflectionException( - "Reflection error: try adding a prefab value for field " + - field.getName() + - " of type " + - field.getType().getName(), - e - ); - } else { + "Reflection error: try adding a prefab value for field " + field.getName() + " of type " + + field.getType().getName(), + e); + } + else { throw e; } } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/InPlaceObjectAccessor.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/InPlaceObjectAccessor.java index 68089fdf8..523c37f91 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/InPlaceObjectAccessor.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/InPlaceObjectAccessor.java @@ -2,6 +2,7 @@ import java.lang.reflect.Field; import java.util.LinkedHashSet; + import nl.jqno.equalsverifier.internal.instantiation.vintage.VintageValueProvider; import nl.jqno.equalsverifier.internal.reflection.FieldIterable; import nl.jqno.equalsverifier.internal.reflection.Instantiator; @@ -16,7 +17,7 @@ final class InPlaceObjectAccessor extends ObjectAccessor { /** Package-private constructor. Call {@link ObjectAccessor#of(Object)} to instantiate. */ - /* default */InPlaceObjectAccessor(T object, Class type) { + /* default */ InPlaceObjectAccessor(T object, Class type) { super(object, type); } @@ -33,10 +34,9 @@ public T copy(Objenesis objenesis) { /** {@inheritDoc} */ @Override public ObjectAccessor scramble( - VintageValueProvider valueProvider, - TypeTag enclosingType, - LinkedHashSet typeStack - ) { + VintageValueProvider valueProvider, + TypeTag enclosingType, + LinkedHashSet typeStack) { for (Field field : FieldIterable.of(type())) { fieldModifierFor(field).changeField(valueProvider, enclosingType, typeStack); } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/ObjectAccessor.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/ObjectAccessor.java index 9fe79aa2c..e2b57efad 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/ObjectAccessor.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/ObjectAccessor.java @@ -1,6 +1,7 @@ package nl.jqno.equalsverifier.internal.instantiation.vintage.reflection; import java.util.LinkedHashSet; + import nl.jqno.equalsverifier.internal.instantiation.vintage.VintageValueProvider; import nl.jqno.equalsverifier.internal.reflection.RecordsHelper; import nl.jqno.equalsverifier.internal.reflection.TypeTag; @@ -17,7 +18,7 @@ public abstract class ObjectAccessor { private final Class type; /** Package private constructor. Call {@link #of(Object)} to instantiate. */ - /* default */ObjectAccessor(T object, Class type) { + /* default */ ObjectAccessor(T object, Class type) { this.object = object; this.type = type; } @@ -25,7 +26,7 @@ public abstract class ObjectAccessor { /** * Factory method. * - * @param {@link #object}'s type. + * @param {@link #object}'s type. * @param object The object to wrap. * @return An {@link ObjectAccessor} for {@link #object}. */ @@ -38,10 +39,9 @@ public static ObjectAccessor of(T object) { /** * Factory method. * - * @param {@link #object}'s type, or a supertype. + * @param {@link #object}'s type, or a supertype. * @param object The object to wrap. - * @param type Superclass of {@link #object}'s type, as which it will be treated by {@link - * ObjectAccessor}. + * @param type Superclass of {@link #object}'s type, as which it will be treated by {@link ObjectAccessor}. * @return An {@link ObjectAccessor} for {@link #object}. */ public static ObjectAccessor of(T object, Class type) { @@ -72,7 +72,8 @@ public Class type() { /** * Creates a copy of the wrapped object. * - *

Note: it does a "shallow" copy. Reference fields are not copied recursively. + *

+ * Note: it does a "shallow" copy. Reference fields are not copied recursively. * * @param objenesis Needed to instantiate the copy. * @return A shallow copy. @@ -80,27 +81,26 @@ public Class type() { public abstract T copy(Objenesis objenesis); /** - * Modifies all fields of the wrapped object that are declared in T and in its superclasses. It - * may or may not mutate the object of the current ObjectAccessor. Either way, the current - * ObjectAccessor and any reference to its object should be considered 'spent' after calling - * this method. The returned ObjectAccessor can safely be used. + * Modifies all fields of the wrapped object that are declared in T and in its superclasses. It may or may not + * mutate the object of the current ObjectAccessor. Either way, the current ObjectAccessor and any reference to its + * object should be considered 'spent' after calling this method. The returned ObjectAccessor can safely be used. * - *

This method is consistent: given two equal objects; after scrambling both objects, they - * remain equal to each other. + *

+ * This method is consistent: given two equal objects; after scrambling both objects, they remain equal to each + * other. * - *

It may not be able to modify: 1. static final fields, and 2. final fields that are - * initialized to a compile-time constant in the field declaration. These fields may be left - * unmodified. + *

+ * It may not be able to modify: 1. static final fields, and 2. final fields that are initialized to a compile-time + * constant in the field declaration. These fields may be left unmodified. * * @param valueProvider Prefabricated values to take values from. - * @param enclosingType Describes the type that contains this object as a field, to determine - * any generic parameters it may contain. - * @param typeStack Keeps track of recursion in the type. + * @param enclosingType Describes the type that contains this object as a field, to determine any generic parameters + * it may contain. + * @param typeStack Keeps track of recursion in the type. * @return An accessor to the scrambled object. */ public abstract ObjectAccessor scramble( - VintageValueProvider valueProvider, - TypeTag enclosingType, - LinkedHashSet typeStack - ); + VintageValueProvider valueProvider, + TypeTag enclosingType, + LinkedHashSet typeStack); } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/RecordObjectAccessor.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/RecordObjectAccessor.java index 425d46da6..597cf5a3c 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/RecordObjectAccessor.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/RecordObjectAccessor.java @@ -5,6 +5,7 @@ import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; + import nl.jqno.equalsverifier.internal.instantiation.vintage.VintageValueProvider; import nl.jqno.equalsverifier.internal.reflection.FieldProbe; import nl.jqno.equalsverifier.internal.reflection.RecordProbe; @@ -12,9 +13,8 @@ import org.objenesis.Objenesis; /** - * Implementation of ObjectAccessor that returns modified copies of its wrapped object, through - * calling its class's constructor. This only works when the constructor matches the class's fields - * exactly, such as in a record. + * Implementation of ObjectAccessor that returns modified copies of its wrapped object, through calling its class's + * constructor. This only works when the constructor matches the class's fields exactly, such as in a record. * * @param The specified object's class. */ @@ -23,7 +23,7 @@ final class RecordObjectAccessor extends ObjectAccessor { private final RecordProbe probe; /** Package-private constructor. Call {@link ObjectAccessor#of(Object)} to instantiate. */ - /* default */RecordObjectAccessor(T object, Class type) { + /* default */ RecordObjectAccessor(T object, Class type) { super(object, type); this.probe = new RecordProbe<>(type); } @@ -38,10 +38,9 @@ public T copy(Objenesis objenesis) { /** {@inheritDoc} */ @Override public ObjectAccessor scramble( - VintageValueProvider valueProvider, - TypeTag enclosingType, - LinkedHashSet typeStack - ) { + VintageValueProvider valueProvider, + TypeTag enclosingType, + LinkedHashSet typeStack) { return makeAccessor(f -> { Object value = getField(f); TypeTag tag = TypeTag.of(f, enclosingType); diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/ClassProbe.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/ClassProbe.java index 18eb2b208..261b93e76 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/ClassProbe.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/ClassProbe.java @@ -77,7 +77,8 @@ private static boolean declaresMethod(Class type, String name, Class... pa try { type.getDeclaredMethod(name, parameterTypes); return true; - } catch (NoSuchMethodException e) { + } + catch (NoSuchMethodException e) { return false; } } @@ -101,16 +102,14 @@ public boolean isHashCodeAbstract() { } private boolean isMethodAbstract(String name, Class... parameterTypes) { - return rethrow(() -> - Modifier.isAbstract(type.getMethod(name, parameterTypes).getModifiers()) - ); + return rethrow(() -> Modifier.isAbstract(type.getMethod(name, parameterTypes).getModifiers())); } /** * Determines whether T's {@code equals} method is inherited from {@link Object}. * - * @return true if T's {@code equals} method is inherited from {@link Object}; false if it is - * overridden in T or in any of its superclasses (except {@link Object}). + * @return true if T's {@code equals} method is inherited from {@link Object}; false if it is overridden in T or in + * any of its superclasses (except {@link Object}). */ public boolean isEqualsInheritedFromObject() { ClassProbe i = this; diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/ConditionalInstantiator.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/ConditionalInstantiator.java index c7fcf7a1f..0d63c8490 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/ConditionalInstantiator.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/ConditionalInstantiator.java @@ -5,6 +5,7 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; + import nl.jqno.equalsverifier.internal.SuppressFBWarnings; import nl.jqno.equalsverifier.internal.exceptions.ReflectionException; @@ -17,8 +18,7 @@ public class ConditionalInstantiator { /** * Constructor. * - * @param fullyQualifiedClassName The fully-qualified name of the class that we intend to - * instantiate. + * @param fullyQualifiedClassName The fully-qualified name of the class that we intend to instantiate. */ public ConditionalInstantiator(String fullyQualifiedClassName) { this(fullyQualifiedClassName, true); @@ -27,9 +27,8 @@ public ConditionalInstantiator(String fullyQualifiedClassName) { /** * Constructor. * - * @param fullyQualifiedClassName The fully-qualified name of the class that we intend to - * instantiate. - * @param throwExceptions Whether to throw exceptions when the class can't be instantiated. + * @param fullyQualifiedClassName The fully-qualified name of the class that we intend to instantiate. + * @param throwExceptions Whether to throw exceptions when the class can't be instantiated. */ public ConditionalInstantiator(String fullyQualifiedClassName, boolean throwExceptions) { this.fullyQualifiedClassName = fullyQualifiedClassName; @@ -49,18 +48,14 @@ public Class resolve() { /** * Attempts to instantiate the type. * - * @param The type to instantiate. - * @param paramTypes The types of the constructor parameters of the constructor that we want to - * call. + * @param The type to instantiate. + * @param paramTypes The types of the constructor parameters of the constructor that we want to call. * @param paramValues The values that we want to pass into the constructor. - * @return An instance of the type given in the constructor with the given parameter values, or - * null if the type does not exist. + * @return An instance of the type given in the constructor with the given parameter values, or null if the type + * does not exist. * @throws ReflectionException If instantiation fails. */ - @SuppressFBWarnings( - value = "DP_DO_INSIDE_DO_PRIVILEGED", - justification = "EV is run only from within unit tests" - ) + @SuppressFBWarnings(value = "DP_DO_INSIDE_DO_PRIVILEGED", justification = "EV is run only from within unit tests") public T instantiate(Class[] paramTypes, Object[] paramValues) { try { Class type = resolve(); @@ -70,7 +65,8 @@ public T instantiate(Class[] paramTypes, Object[] paramValues) { Constructor c = type.getConstructor(paramTypes); c.setAccessible(true); return c.newInstance(paramValues); - } catch (Exception e) { + } + catch (Exception e) { return handleException(e); } } @@ -78,13 +74,12 @@ public T instantiate(Class[] paramTypes, Object[] paramValues) { /** * Attempts to call a static factory method on the type. * - * @param The return type of the factory method. + * @param The return type of the factory method. * @param factoryMethod The name of the factory method. - * @param paramTypes The types of the parameters of the specific overload of the factory method - * we want to call. - * @param paramValues The values that we want to pass into the factory method. - * @return An instance of the type given by the factory method with the given parameter values, - * or null of the type does not exist. + * @param paramTypes The types of the parameters of the specific overload of the factory method we want to call. + * @param paramValues The values that we want to pass into the factory method. + * @return An instance of the type given by the factory method with the given parameter values, or null of the type + * does not exist. * @throws ReflectionException If the call to the factory method fails. */ public T callFactory(String factoryMethod, Class[] paramTypes, Object[] paramValues) { @@ -94,27 +89,23 @@ public T callFactory(String factoryMethod, Class[] paramTypes, Object[] p /** * Attempts to call a static factory method on a type. * - * @param The return type of the factory method. + * @param The return type of the factory method. * @param factoryTypeName The type that contains the factory method. - * @param factoryMethod The name of the factory method. - * @param paramTypes The types of the parameters of the specific overload of the factory method - * we want to call. - * @param paramValues The values that we want to pass into the factory method. - * @return An instance of the type given by the factory method with the given parameter values, - * or null of the type does not exist. + * @param factoryMethod The name of the factory method. + * @param paramTypes The types of the parameters of the specific overload of the factory method we want to + * call. + * @param paramValues The values that we want to pass into the factory method. + * @return An instance of the type given by the factory method with the given parameter values, or null of the type + * does not exist. * @throws ReflectionException If the call to the factory method fails. */ - @SuppressFBWarnings( - value = "DP_DO_INSIDE_DO_PRIVILEGED", - justification = "EV is run only from within unit tests" - ) + @SuppressFBWarnings(value = "DP_DO_INSIDE_DO_PRIVILEGED", justification = "EV is run only from within unit tests") @SuppressWarnings("unchecked") public T callFactory( - String factoryTypeName, - String factoryMethod, - Class[] paramTypes, - Object[] paramValues - ) { + String factoryTypeName, + String factoryMethod, + Class[] paramTypes, + Object[] paramValues) { try { Class type = resolve(); if (type == null) { @@ -124,7 +115,8 @@ public T callFactory( Method factory = factoryType.getMethod(factoryMethod, paramTypes); factory.setAccessible(true); return (T) factory.invoke(null, paramValues); - } catch (Exception e) { + } + catch (Exception e) { return handleException(e); } } @@ -132,15 +124,12 @@ public T callFactory( /** * Attempts to resolve a static constant on the type. * - * @param The type of the constant. + * @param The type of the constant. * @param constantName The name of the constant. * @return The value of the constant, or null if the type does not exist. * @throws ReflectionException If resolving the constant fails. */ - @SuppressFBWarnings( - value = "DP_DO_INSIDE_DO_PRIVILEGED", - justification = "EV is run only from within unit tests" - ) + @SuppressFBWarnings(value = "DP_DO_INSIDE_DO_PRIVILEGED", justification = "EV is run only from within unit tests") @SuppressWarnings("unchecked") public T returnConstant(String constantName) { try { @@ -151,7 +140,8 @@ public T returnConstant(String constantName) { Field field = type.getField(constantName); field.setAccessible(true); return (T) field.get(null); - } catch (Exception e) { + } + catch (Exception e) { return handleException(e); } } @@ -159,7 +149,8 @@ public T returnConstant(String constantName) { private T handleException(Exception e) { if (throwExceptions) { throw new ReflectionException(e); - } else { + } + else { return null; } } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/FieldCache.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/FieldCache.java index 28856ac6f..f52e88c7d 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/FieldCache.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/FieldCache.java @@ -1,23 +1,24 @@ package nl.jqno.equalsverifier.internal.reflection; import java.util.*; + import nl.jqno.equalsverifier.internal.instantiation.SubjectCreator; /** Contains a cache for values connected to specific fields, for {@link SubjectCreator}. */ public class FieldCache { /** - * We store Strings instead of Fields, to make it easier to interact with when we don't - * actually have a reference to a Field. + * We store Strings instead of Fields, to make it easier to interact with when we don't actually have a reference to + * a Field. */ private final Map> cache = new HashMap<>(); /** * Adds the given factory to the cache and associates it with the given type. * - * @param The type of the values. + * @param The type of the values. * @param fieldName The name of the field to associate with the values. - * @param tuple The tuple that contains the values. + * @param tuple The tuple that contains the values. */ public void put(String fieldName, Tuple tuple) { if (fieldName != null) { @@ -28,10 +29,10 @@ public void put(String fieldName, Tuple tuple) { /** * Retrieves the values from the cache for the given field. * - *

What happens when there are no values, is undefined. Always call {@link #contains(String)} - * first. + *

+ * What happens when there are no values, is undefined. Always call {@link #contains(String)} first. * - * @param The returned values will have this as generic type. + * @param The returned values will have this as generic type. * @param fieldName The name of the field for which values are needed. * @return A tuple of values for the given type, or {@code null} if none is available. */ diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/FieldIterable.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/FieldIterable.java index aa9ec66c6..9ebe630d5 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/FieldIterable.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/FieldIterable.java @@ -6,8 +6,7 @@ import java.util.List; /** - * Iterable to iterate over all declared fields in a class and, if needed, over all declared fields - * of its superclasses. + * Iterable to iterate over all declared fields in a class and, if needed, over all declared fields of its superclasses. */ public final class FieldIterable implements Iterable { @@ -23,8 +22,8 @@ private FieldIterable(Class type, boolean includeSuperclasses, boolean includ } /** - * Factory method for a FieldIterable that iterates over all declared fields of {@code type} and - * over the declared fields of all of its superclasses. + * Factory method for a FieldIterable that iterates over all declared fields of {@code type} and over the declared + * fields of all of its superclasses. * * @param type The class that contains the fields over which to iterate. * @return A FieldIterable. @@ -34,8 +33,8 @@ public static FieldIterable of(Class type) { } /** - * Factory method for a FieldIterable that iterates over all declared fields of {@code type}, - * but that ignores the declared fields of its superclasses. + * Factory method for a FieldIterable that iterates over all declared fields of {@code type}, but that ignores the + * declared fields of its superclasses. * * @param type The class that contains the fields over which to iterate. * @return A FieldIterable. @@ -45,8 +44,8 @@ public static FieldIterable ofIgnoringSuper(Class type) { } /** - * Factory method for a FieldIterable that iterates over all declared fields of {@code type}, - * but that ignores its static fields. + * Factory method for a FieldIterable that iterates over all declared fields of {@code type}, but that ignores its + * static fields. * * @param type The class that contains the fields over which to iterate. * @return A FieldIterable. @@ -56,8 +55,8 @@ public static FieldIterable ofIgnoringStatic(Class type) { } /** - * Factory method for a FieldIterable that iterates over all declared fields of {@code type}, - * but that ignores its the declared fields of its superclasses, as well as its static fields. + * Factory method for a FieldIterable that iterates over all declared fields of {@code type}, but that ignores its + * the declared fields of its superclasses, as well as its static fields. * * @param type The class that contains the fields over which to iterate. * @return A FieldIterable. @@ -95,10 +94,9 @@ private List addFieldsFor(Class c) { List statics = new ArrayList<>(); for (Field field : c.getDeclaredFields()) { - if ( - !field.isSynthetic() && - !"__cobertura_counters".equals(field.getName()) && - !field.getName().startsWith("bitmap$init$") // Generated by Scala 2.x's -Xcheckinit flag + if (!field.isSynthetic() + && !"__cobertura_counters".equals(field.getName()) + && !field.getName().startsWith("bitmap$init$") // Generated by Scala 2.x's -Xcheckinit flag ) { boolean isStatic = FieldProbe.of(field).isStatic(); if (isStatic && includeStatic) { diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/FieldMutator.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/FieldMutator.java index f27805935..e9af98c3a 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/FieldMutator.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/FieldMutator.java @@ -25,7 +25,7 @@ public FieldMutator(FieldProbe probe) { /** * Assigns {@code newValue} to the current field in {@code object}. * - * @param object The instance on which to re-assign the current field. + * @param object The instance on which to re-assign the current field. * @param newValue The value to assign to the field. */ public void setNewValue(Object object, Object newValue) { diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/FieldProbe.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/FieldProbe.java index 63012e644..b63324392 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/FieldProbe.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/FieldProbe.java @@ -5,6 +5,7 @@ import java.lang.reflect.Field; import java.lang.reflect.Modifier; + import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.SuppressFBWarnings; import nl.jqno.equalsverifier.internal.exceptions.ReflectionException; @@ -47,9 +48,8 @@ public Field getField() { * @throws ReflectionException If the operation fails. */ @SuppressFBWarnings( - value = "DP_DO_INSIDE_DO_PRIVILEGED", - justification = "Only called in test code, not production." - ) + value = "DP_DO_INSIDE_DO_PRIVILEGED", + justification = "Only called in test code, not production.") public Object getValue(Object object) { field.setAccessible(true); return rethrow(() -> field.get(object)); @@ -102,16 +102,12 @@ public boolean canBeDefault(Configuration config) { boolean isAnnotated = isAnnotatedNonnull(config.getAnnotationCache()); boolean isMentionedExplicitly = config.getNonnullFields().contains(field.getName()); - return ( - !config.getWarningsToSuppress().contains(Warning.NULL_FIELDS) && - !isAnnotated && - !isMentionedExplicitly - ); + return !config.getWarningsToSuppress().contains(Warning.NULL_FIELDS) && !isAnnotated && !isMentionedExplicitly; } /** - * Checks whether the given field is marked with an Nonnull annotation, whether directly, or - * through some default annotation mechanism. + * Checks whether the given field is marked with an Nonnull annotation, whether directly, or through some default + * annotation mechanism. * * @param annotationCache To retrieve annotations from. * @return True if the field is to be treated as Nonnull. @@ -124,18 +120,9 @@ public boolean isAnnotatedNonnull(AnnotationCache annotationCache) { if (annotationCache.hasFieldAnnotation(type, field.getName(), NULLABLE)) { return false; } - boolean hasFindbugsAnnotation = annotationCache.hasClassAnnotation( - type, - FINDBUGS1X_DEFAULT_ANNOTATION_NONNULL - ); - boolean hasJsr305Annotation = annotationCache.hasClassAnnotation( - type, - JSR305_DEFAULT_ANNOTATION_NONNULL - ); - boolean hasDefaultAnnotation = annotationCache.hasClassAnnotation( - type, - DEFAULT_ANNOTATION_NONNULL - ); + boolean hasFindbugsAnnotation = annotationCache.hasClassAnnotation(type, FINDBUGS1X_DEFAULT_ANNOTATION_NONNULL); + boolean hasJsr305Annotation = annotationCache.hasClassAnnotation(type, JSR305_DEFAULT_ANNOTATION_NONNULL); + boolean hasDefaultAnnotation = annotationCache.hasClassAnnotation(type, DEFAULT_ANNOTATION_NONNULL); return hasFindbugsAnnotation || hasJsr305Annotation || hasDefaultAnnotation; } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/Instantiator.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/Instantiator.java index b83e0b883..862bc9bf8 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/Instantiator.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/Instantiator.java @@ -9,6 +9,7 @@ import java.util.Arrays; import java.util.List; import java.util.function.UnaryOperator; + import net.bytebuddy.ByteBuddy; import net.bytebuddy.dynamic.DynamicType; import net.bytebuddy.dynamic.loading.ClassLoadingStrategy; @@ -19,18 +20,12 @@ /** * Instantiates objects of a given class. * - * @param {@link Instantiator} instantiates objects of this class, or of an anonymous subclass - * of this class. + * @param {@link Instantiator} instantiates objects of this class, or of an anonymous subclass of this class. */ public final class Instantiator { - private static final List FORBIDDEN_PACKAGES = Arrays.asList( - "java.", - "javax.", - "sun.", - "com.sun.", - "org.w3c.dom." - ); + private static final List FORBIDDEN_PACKAGES = + Arrays.asList("java.", "javax.", "sun.", "com.sun.", "org.w3c.dom."); private static final String FALLBACK_PACKAGE_NAME = getPackageName(Instantiator.class); private final Class type; @@ -47,8 +42,8 @@ private Instantiator(Class type, Objenesis objenesis) { /** * Factory method. * - * @param The class on which {@link Instantiator} operates. - * @param type The class on which {@link Instantiator} operates. Should be the same as T. + * @param The class on which {@link Instantiator} operates. + * @param type The class on which {@link Instantiator} operates. Should be the same as T. * @param objenesis To instantiate non-record classes. * @return An {@link Instantiator} for {@link #type}. */ @@ -66,8 +61,8 @@ public static Instantiator of(Class type, Objenesis objenesis) { /** * Instantiates an object of type T. * - *

All fields will be initialized to their initial values. I.e., 0 for ints, null for - * objects, etc. + *

+ * All fields will be initialized to their initial values. I.e., 0 for ints, null for objects, etc. * * @return An object of type T. */ @@ -91,21 +86,14 @@ public static Class giveDynamicSubclass(Class superclass) { @SuppressWarnings("unchecked") public static synchronized Class giveDynamicSubclass( - Class superclass, - String nameSuffix, - UnaryOperator> modify - ) { + Class superclass, + String nameSuffix, + UnaryOperator> modify) { boolean isSystemClass = isSystemClass(superclass.getName()); String namePrefix = isSystemClass ? FALLBACK_PACKAGE_NAME : getPackageName(superclass); - String name = - namePrefix + - (namePrefix.isEmpty() ? "" : ".") + - superclass.getSimpleName() + - "$$DynamicSubclass$" + - Integer.toHexString(superclass.hashCode()) + - "$" + - nameSuffix; + String name = namePrefix + (namePrefix.isEmpty() ? "" : ".") + superclass.getSimpleName() + "$$DynamicSubclass$" + + Integer.toHexString(superclass.hashCode()) + "$" + nameSuffix; Class context = isSystemClass ? Instantiator.class : superclass; ClassLoader classLoader = context.getClassLoader(); @@ -118,10 +106,7 @@ public static synchronized Class giveDynamicSubclass( } ClassLoadingStrategy cs = getClassLoadingStrategy(context); - DynamicType.Builder builder = new ByteBuddy() - .with(TypeValidation.DISABLED) - .subclass(superclass) - .name(name); + DynamicType.Builder builder = new ByteBuddy().with(TypeValidation.DISABLED).subclass(superclass).name(name); builder = modify.apply(builder); @@ -131,22 +116,21 @@ public static synchronized Class giveDynamicSubclass( private static String getPackageName(Class type) { String cn = type.getName(); int dot = cn.lastIndexOf('.'); - return (dot != -1) ? cn.substring(0, dot).intern() : ""; + return dot != -1 ? cn.substring(0, dot).intern() : ""; } private static ClassLoadingStrategy getClassLoadingStrategy(Class context) { if (System.getProperty("java.version").startsWith("1.")) { return ClassLoadingStrategy.Default.INJECTION.with(context.getProtectionDomain()); - } else { - ConditionalInstantiator ci = new ConditionalInstantiator( - "java.lang.invoke.MethodHandles$Lookup" - ); - Object lookup = ci.callFactory( - "java.lang.invoke.MethodHandles", - "privateLookupIn", - classes(Class.class, MethodHandles.Lookup.class), - objects(context, MethodHandles.lookup()) - ); + } + else { + ConditionalInstantiator ci = new ConditionalInstantiator("java.lang.invoke.MethodHandles$Lookup"); + Object lookup = ci + .callFactory( + "java.lang.invoke.MethodHandles", + "privateLookupIn", + classes(Class.class, MethodHandles.Lookup.class), + objects(context, MethodHandles.lookup())); return ClassLoadingStrategy.UsingLookup.of(lookup); } } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/ModuleHelper.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/ModuleHelper.java index b7f05028b..9602f7380 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/ModuleHelper.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/ModuleHelper.java @@ -1,8 +1,7 @@ package nl.jqno.equalsverifier.internal.reflection; /** - * Note: this is a generic implementation for a multi-release jar class. - * See equalsverifier-11 submodule. + * Note: this is a generic implementation for a multi-release jar class. See equalsverifier-11 submodule. */ public final class ModuleHelper { diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/PackageScanner.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/PackageScanner.java index 116a13872..96d5512e7 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/PackageScanner.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/PackageScanner.java @@ -18,91 +18,68 @@ private PackageScanner() {} /** * Scans the given package for classes. * - * Note that if {@code mustExtend} is given, and it exists within {@code packageName}, - * it will NOT be included. + * Note that if {@code mustExtend} is given, and it exists within {@code packageName}, it will NOT be included. * - * @param packageName The package to scan. - * @param mustExtend if not null, returns only classes that extend or implement this class. + * @param packageName The package to scan. + * @param mustExtend if not null, returns only classes that extend or implement this class. * @param scanRecursively true to scan all sub-packages * @return the classes contained in the given package. */ - public static List> getClassesIn( - String packageName, - Class mustExtend, - boolean scanRecursively - ) { + public static List> getClassesIn(String packageName, Class mustExtend, boolean scanRecursively) { return getDirs(packageName) - .stream() - .flatMap(d -> getClassesInDir(packageName, d, mustExtend, scanRecursively).stream()) - .collect(Collectors.toList()); + .stream() + .flatMap(d -> getClassesInDir(packageName, d, mustExtend, scanRecursively).stream()) + .collect(Collectors.toList()); } private static List getDirs(String packageName) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); String path = packageName.replace('.', '/'); return rethrow( - () -> - Collections + () -> Collections .list(cl.getResources(path)) .stream() .map(r -> new File(getResourcePath(r))) .collect(Collectors.toList()), - e -> "Could not scan package " + packageName - ); + e -> "Could not scan package " + packageName); } private static String getResourcePath(URL r) { - return rethrow( - () -> r.toURI().getPath(), - e -> "Could not resolve resource path: " + e.getMessage() - ); + return rethrow(() -> r.toURI().getPath(), e -> "Could not resolve resource path: " + e.getMessage()); } private static List> getClassesInDir( - String packageName, - File dir, - Class mustExtend, - boolean scanRecursively - ) { + String packageName, + File dir, + Class mustExtend, + boolean scanRecursively) { if (!dir.exists()) { return Collections.emptyList(); } return Arrays - .stream(dir.listFiles()) - .filter(f -> (scanRecursively && f.isDirectory()) || f.getName().endsWith(".class")) - .flatMap(f -> { - List> classes; - if (f.isDirectory()) { - classes = - getClassesInDir( - packageName + "." + f.getName(), - f, - mustExtend, - scanRecursively - ); - } else { - classes = Collections.singletonList(fileToClass(packageName, f)); - } - return classes.stream(); - }) - .filter(c -> !c.isAnonymousClass()) - .filter(c -> !c.isLocalClass()) - .filter(c -> !c.getName().endsWith("Test")) - .filter(c -> - mustExtend == null || (mustExtend.isAssignableFrom(c) && !mustExtend.equals(c)) - ) - .collect(Collectors.toList()); + .stream(dir.listFiles()) + .filter(f -> (scanRecursively && f.isDirectory()) || f.getName().endsWith(".class")) + .flatMap(f -> { + List> classes; + if (f.isDirectory()) { + classes = getClassesInDir(packageName + "." + f.getName(), f, mustExtend, scanRecursively); + } + else { + classes = Collections.singletonList(fileToClass(packageName, f)); + } + return classes.stream(); + }) + .filter(c -> !c.isAnonymousClass()) + .filter(c -> !c.isLocalClass()) + .filter(c -> !c.getName().endsWith("Test")) + .filter(c -> mustExtend == null || (mustExtend.isAssignableFrom(c) && !mustExtend.equals(c))) + .collect(Collectors.toList()); } private static Class fileToClass(String packageName, File file) { String className = file.getName().substring(0, file.getName().length() - 6); return rethrow( () -> Class.forName(packageName + "." + className), - e -> - "Could not resolve class " + - className + - ", which was found in package " + - packageName - ); + e -> "Could not resolve class " + className + ", which was found in package " + packageName); } } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/RecordProbe.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/RecordProbe.java index 4cbaecbf7..2fe154a81 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/RecordProbe.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/RecordProbe.java @@ -8,6 +8,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; + import nl.jqno.equalsverifier.internal.util.PrimitiveMappers; public class RecordProbe { @@ -24,38 +25,25 @@ public Stream fields() { public T callRecordConstructor(List params) { Constructor constructor = getRecordConstructor(); - return rethrow( - () -> constructor.newInstance(params.toArray(new Object[0])), - e -> buildMessage(e, params) - ); + return rethrow(() -> constructor.newInstance(params.toArray(new Object[0])), e -> buildMessage(e, params)); } private Constructor getRecordConstructor() { return rethrow(() -> { - List> constructorTypes = fields() - .map(Field::getType) - .collect(Collectors.toList()); - Constructor result = type.getDeclaredConstructor( - constructorTypes.toArray(new Class[0]) - ); + List> constructorTypes = fields().map(Field::getType).collect(Collectors.toList()); + Constructor result = type.getDeclaredConstructor(constructorTypes.toArray(new Class[0])); result.setAccessible(true); return result; }); } private String buildMessage(Throwable e, List params) { - String prefix = - "Record: failed to run constructor for record type " + - type.getName() + - "\n These were the values passed to the constructor: " + - params; + String prefix = "Record: failed to run constructor for record type " + type.getName() + + "\n These were the values passed to the constructor: " + params; if (e.getCause() instanceof NullPointerException) { - return ( - prefix + - "\n If the record does not accept null values for its constructor parameters," + - " consider suppressing Warning.NULL_FIELDS." - ); + return prefix + "\n If the record does not accept null values for its constructor parameters," + + " consider suppressing Warning.NULL_FIELDS."; } boolean hasZeros = false; @@ -63,7 +51,8 @@ private String buildMessage(Throwable e, List params) { for (Object p : params) { if (PrimitiveMappers.ZEROS.contains(p)) { hasZeros = true; - } else { + } + else { // nulls are already eliminated hasSomethingElse = true; } @@ -71,14 +60,12 @@ private String buildMessage(Throwable e, List params) { String msg = prefix; if (hasZeros) { - msg += - "\n If the record does not accept 0 or false as a value for its constructor parameters," + - " consider suppressing Warning.ZERO_FIELDS."; + msg += "\n If the record does not accept 0 or false as a value for its constructor parameters," + + " consider suppressing Warning.ZERO_FIELDS."; } if (hasSomethingElse) { - msg += - "\n If the record does not accept any of the given values for its constructor parameters," + - " consider providing prefab values for the types of those fields."; + msg += "\n If the record does not accept any of the given values for its constructor parameters," + + " consider providing prefab values for the types of those fields."; } return msg; } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/RecordsHelper.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/RecordsHelper.java index 521e00311..fe2515d41 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/RecordsHelper.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/RecordsHelper.java @@ -1,8 +1,7 @@ package nl.jqno.equalsverifier.internal.reflection; /** - * Note: this is a generic implementation for a multi-release jar class. - * See equalsverifier-16 submodule. + * Note: this is a generic implementation for a multi-release jar class. See equalsverifier-16 submodule. */ public final class RecordsHelper { diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/SealedTypesHelper.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/SealedTypesHelper.java index a93467f79..8b6d7092c 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/SealedTypesHelper.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/SealedTypesHelper.java @@ -3,8 +3,7 @@ import java.util.Optional; /** - * Note: this is a generic implementation for a multi-release jar class. - * See equalsverifier-17 submodule. + * Note: this is a generic implementation for a multi-release jar class. See equalsverifier-17 submodule. */ public final class SealedTypesHelper { diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/SuperclassIterable.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/SuperclassIterable.java index 33ca951f6..ce5ac0778 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/SuperclassIterable.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/SuperclassIterable.java @@ -17,11 +17,11 @@ private SuperclassIterable(Class type, boolean includeSelf) { } /** - * Factory method for a SuperlcassIterator that iterates over type's superclasses, excluding - * itself and excluding Object. + * Factory method for a SuperlcassIterator that iterates over type's superclasses, excluding itself and excluding + * Object. * * @param type The class over whose superclasses to iterate. - * @param Type parameter for type. + * @param Type parameter for type. * @return A SuperclassIterator. */ public static SuperclassIterable of(Class type) { @@ -29,11 +29,11 @@ public static SuperclassIterable of(Class type) { } /** - * Factory method for a SuperlcassIterator that iterates over type's superclasses, including - * itself but excluding Object. + * Factory method for a SuperlcassIterator that iterates over type's superclasses, including itself but excluding + * Object. * * @param type The class over whose superclasses to iterate. - * @param Type parameter for type. + * @param Type parameter for type. * @return A SuperclassIterator. */ public static SuperclassIterable ofIncludeSelf(Class type) { @@ -41,8 +41,8 @@ public static SuperclassIterable ofIncludeSelf(Class type) { } /** - * Returns an iterator over all superclasses of the class. Is empty if type has no superclasses - * and SuperclassIterable does not include self. + * Returns an iterator over all superclasses of the class. Is empty if type has no superclasses and + * SuperclassIterable does not include self. * * @return The iterator. */ diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/Tuple.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/Tuple.java index c276f3fac..c6fb88e61 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/Tuple.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/Tuple.java @@ -1,8 +1,7 @@ package nl.jqno.equalsverifier.internal.reflection; /** - * Container for three values of the same type: a "red" one, a "blue" one, and a shallow copy of the - * "red" one. + * Container for three values of the same type: a "red" one, a "blue" one, and a shallow copy of the "red" one. */ public final class Tuple { @@ -13,8 +12,8 @@ public final class Tuple { /** * Constructor. * - * @param red The red value. - * @param blue The blue value. + * @param red The red value. + * @param blue The blue value. * @param redCopy A shallow copy of the red value. */ public Tuple(T red, T blue, T redCopy) { @@ -26,10 +25,10 @@ public Tuple(T red, T blue, T redCopy) { /** * Factory method that turns three untyped values into a typed tuple. * - * @param red The red value. - * @param blue The blue value. + * @param red The red value. + * @param blue The blue value. * @param redCopy A shallow copy of the red value. - * @param The assumed type of the values. + * @param The assumed type of the values. * @return A typed tuple with the three given values. */ @SuppressWarnings("unchecked") diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/TypeTag.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/TypeTag.java index 09b30a6e8..3cc21adda 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/TypeTag.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/TypeTag.java @@ -4,12 +4,14 @@ import java.lang.reflect.*; import java.util.*; + import nl.jqno.equalsverifier.internal.exceptions.EqualsVerifierInternalBugException; /** * Represents a generic type, including raw type and generic type parameters. * - *

If the type is not generic, the genericTypes list will be empty. + *

+ * If the type is not generic, the genericTypes list will be empty. */ public final class TypeTag { @@ -22,7 +24,7 @@ public final class TypeTag { /** * Constructor. * - * @param type The raw type. + * @param type The raw type. * @param genericTypes A list of TypeTags for each generic type parameter. */ public TypeTag(Class type, TypeTag... genericTypes) { @@ -38,12 +40,11 @@ private TypeTag(Class type, List genericTypes) { } /** - * Resolves a TypeTag from the type of a {@link Field} instance, using an enclosing type to - * determine any generic parameters the field may contain. + * Resolves a TypeTag from the type of a {@link Field} instance, using an enclosing type to determine any generic + * parameters the field may contain. * - * @param field The field to resolve. - * @param enclosingType The type that contains the field, used to determine any generic - * parameters it may contain. + * @param field The field to resolve. + * @param enclosingType The type that contains the field, used to determine any generic parameters it may contain. * @return The TypeTag for the given field. */ public static TypeTag of(Field field, TypeTag enclosingType) { @@ -51,11 +52,10 @@ public static TypeTag of(Field field, TypeTag enclosingType) { } private static TypeTag resolve( - Type type, - Class typeAsClass, - TypeTag enclosingType, - boolean shortCircuitRecursiveTypeBound - ) { + Type type, + Class typeAsClass, + TypeTag enclosingType, + boolean shortCircuitRecursiveTypeBound) { List nestedTags = new ArrayList<>(); if (type instanceof Class) { return processClass((Class) type, nestedTags); @@ -66,31 +66,23 @@ private static TypeTag resolve( typeAsClass, enclosingType, nestedTags, - shortCircuitRecursiveTypeBound - ); + shortCircuitRecursiveTypeBound); } if (type instanceof GenericArrayType) { return processGenericArray((GenericArrayType) type, typeAsClass, enclosingType); } if (type instanceof WildcardType) { - return processWildcard( - (WildcardType) type, - typeAsClass, - enclosingType, - shortCircuitRecursiveTypeBound - ); + return processWildcard((WildcardType) type, typeAsClass, enclosingType, shortCircuitRecursiveTypeBound); } if (type instanceof TypeVariable) { return processTypeVariable( (TypeVariable) type, typeAsClass, enclosingType, - shortCircuitRecursiveTypeBound - ); + shortCircuitRecursiveTypeBound); } throw new EqualsVerifierInternalBugException( - "Failed to tag type " + type.toString() + " (" + type.getClass() + ")" - ); + "Failed to tag type " + type.toString() + " (" + type.getClass() + ")"); } private static TypeTag processClass(Class type, List nestedTags) { @@ -98,26 +90,19 @@ private static TypeTag processClass(Class type, List nestedTags) { } private static TypeTag processParameterizedType( - ParameterizedType type, - Class typeAsClass, - TypeTag enclosingType, - List nestedTags, - boolean shortCircuitRecursiveTypeBound - ) { + ParameterizedType type, + Class typeAsClass, + TypeTag enclosingType, + List nestedTags, + boolean shortCircuitRecursiveTypeBound) { Type[] typeArgs = type.getActualTypeArguments(); for (Type typeArg : typeArgs) { - nestedTags.add( - resolve(typeArg, typeAsClass, enclosingType, shortCircuitRecursiveTypeBound) - ); + nestedTags.add(resolve(typeArg, typeAsClass, enclosingType, shortCircuitRecursiveTypeBound)); } return new TypeTag((Class) type.getRawType(), nestedTags); } - private static TypeTag processGenericArray( - GenericArrayType type, - Class typeAsClass, - TypeTag enclosingType - ) { + private static TypeTag processGenericArray(GenericArrayType type, Class typeAsClass, TypeTag enclosingType) { TypeTag tag = resolve(type.getGenericComponentType(), typeAsClass, enclosingType, false); String arrayTypeName = "[L" + tag.getType().getName() + ";"; Class arrayType = classForName(arrayTypeName); @@ -125,11 +110,10 @@ private static TypeTag processGenericArray( } private static TypeTag processWildcard( - WildcardType type, - Class typeAsClass, - TypeTag enclosingType, - boolean shortCircuitRecursiveTypeBound - ) { + WildcardType type, + Class typeAsClass, + TypeTag enclosingType, + boolean shortCircuitRecursiveTypeBound) { for (Type b : type.getLowerBounds()) { return resolve(b, typeAsClass, enclosingType, shortCircuitRecursiveTypeBound); } @@ -148,11 +132,10 @@ private static TypeTag processWildcard( } private static TypeTag processTypeVariable( - TypeVariable type, - Class typeAsClass, - TypeTag enclosingType, - boolean shortCircuitRecursiveTypeBound - ) { + TypeVariable type, + Class typeAsClass, + TypeTag enclosingType, + boolean shortCircuitRecursiveTypeBound) { Map typeVariableLookup = buildLookup(enclosingType); String typeVariableName = type.getName(); if (typeVariableLookup.containsKey(typeVariableName)) { diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/Util.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/Util.java index 5720a2b03..429d9c25a 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/Util.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/Util.java @@ -14,14 +14,15 @@ private Util() { * Helper method to resolve a Class of a given name. * * @param className The fully qualified name of the class to resolve. - * @param The type of the class to resolve. + * @param The type of the class to resolve. * @return The corresponding class if it exists, null otherwise. */ @SuppressWarnings("unchecked") public static Class classForName(String className) { try { return (Class) Class.forName(className); - } catch (ClassNotFoundException | VerifyError e) { + } + catch (ClassNotFoundException | VerifyError e) { // Catching VerifyError fixes issue #147. I don't know how to unit test it. return null; } @@ -31,15 +32,16 @@ public static Class classForName(String className) { * Helper method to resolve a Class of a given name through a given ClassLoader. * * @param classLoader The class loader to resolve the class against. - * @param className The fully qualified name of the class to resolve. - * @param The type of the class to resolve. + * @param className The fully qualified name of the class to resolve. + * @param The type of the class to resolve. * @return The corresponding class if it exists, null otherwise. */ @SuppressWarnings("unchecked") public static Class classForName(ClassLoader classLoader, String className) { try { return (Class) classLoader.loadClass(className); - } catch (ClassNotFoundException | VerifyError e) { + } + catch (ClassNotFoundException | VerifyError e) { // Catching VerifyError fixes issue #147. I don't know how to unit test it. return null; } @@ -77,7 +79,7 @@ public static Object[] objects(Object first) { /** * Helper method to create an array of Objects. * - * @param first The first object to construct an array out of. + * @param first The first object to construct an array out of. * @param second The second object in the array. * @return An array with the given objects. */ @@ -88,9 +90,9 @@ public static Object[] objects(Object first, Object second) { /** * Helper method to create an array of Objects. * - * @param first The first object to construct an array out of. + * @param first The first object to construct an array out of. * @param second The second object in the array. - * @param third The third object in the array. + * @param third The third object in the array. * @return An array with the given objects. */ public static Object[] objects(Object first, Object second, Object third) { @@ -100,7 +102,7 @@ public static Object[] objects(Object first, Object second, Object third) { /** * Helper method to create a set of object. * - * @param ts The objects to add to the set. + * @param ts The objects to add to the set. * @param The type of objects to add to the set. * @return A set with the given objets. */ diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/annotations/Annotation.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/annotations/Annotation.java index 60b36ba2d..51edccec2 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/annotations/Annotation.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/annotations/Annotation.java @@ -5,55 +5,55 @@ /** * Describes an annotation that can be recognised by EqualsVerifier. * - *

The annotation can have {@link java.lang.annotation.RetentionPolicy#RUNTIME} or {@link - * java.lang.annotation.RetentionPolicy#CLASS}, and must have either {@link - * java.lang.annotation.ElementType#TYPE} or {@link java.lang.annotation.ElementType#FIELD}. + *

+ * The annotation can have {@link java.lang.annotation.RetentionPolicy#RUNTIME} or + * {@link java.lang.annotation.RetentionPolicy#CLASS}, and must have either + * {@link java.lang.annotation.ElementType#TYPE} or {@link java.lang.annotation.ElementType#FIELD}. */ public interface Annotation { /** - * One or more strings that contain the annotation's (partial) class name. This can be the - * annotation's fully qualified canonical name, or a substring thereof. + * One or more strings that contain the annotation's (partial) class name. This can be the annotation's fully + * qualified canonical name, or a substring thereof. * - *

An annotation can be described by more than one partial class name. For - * instance, @Nonnull, @NonNull and @NotNull have the same semantics; their partialClassNames - * can be grouped together in one {@link Annotation} instance. + *

+ * An annotation can be described by more than one partial class name. For instance, @Nonnull, @NonNull and @NotNull + * have the same semantics; their partialClassNames can be grouped together in one {@link Annotation} instance. * * @return A Set of potentially partial annotation class names. */ Set partialClassNames(); /** - * Whether the annotation applies to the class in which is appears only, or whether it applies - * to that class and all its subclasses. + * Whether the annotation applies to the class in which is appears only, or whether it applies to that class and all + * its subclasses. * - *

Note: this encompasses more than {@link java.lang.annotation.Inherited} does: this flag - * also applies, for example, to annotations on fields that are declared in a superclass. + *

+ * Note: this encompasses more than {@link java.lang.annotation.Inherited} does: this flag also applies, for + * example, to annotations on fields that are declared in a superclass. * - * @return True if the annotation is inherited by subclasses of the class in which the - * annotation appears. + * @return True if the annotation is inherited by subclasses of the class in which the annotation appears. */ boolean inherits(); /** * Validates the annotation based on its properties. * - * @param properties An object that contains information about the annotation. - * @param annotationCache A cache containing all annotations for known types. + * @param properties An object that contains information about the annotation. + * @param annotationCache A cache containing all annotations for known types. * @param ignoredAnnotations A collection of type partialClassNames for annotations to ignore. * @return True if the annotation is valid and can be used as intended. */ default boolean validate( - AnnotationProperties properties, - AnnotationCache annotationCache, - Set ignoredAnnotations - ) { + AnnotationProperties properties, + AnnotationCache annotationCache, + Set ignoredAnnotations) { return true; } /** * Performs post processing after the annotation was added to the cache. * - * @param types The types that the annotation applies to. + * @param types The types that the annotation applies to. * @param annotationCache A cache containing all annotations for known types. */ default void postProcess(Set> types, AnnotationCache annotationCache) {} diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/annotations/AnnotationCacheBuilder.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/annotations/AnnotationCacheBuilder.java index 88012cca1..bc2f24cc7 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/annotations/AnnotationCacheBuilder.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/annotations/AnnotationCacheBuilder.java @@ -8,6 +8,7 @@ import java.util.List; import java.util.Set; import java.util.function.Consumer; + import net.bytebuddy.description.annotation.AnnotationDescription; import net.bytebuddy.description.enumeration.EnumerationDescription; import net.bytebuddy.description.field.FieldDescription; @@ -22,10 +23,7 @@ public class AnnotationCacheBuilder { private final List supportedAnnotations; private final Set ignoredAnnotations; - public AnnotationCacheBuilder( - Annotation[] supportedAnnotations, - Set ignoredAnnotations - ) { + public AnnotationCacheBuilder(Annotation[] supportedAnnotations, Set ignoredAnnotations) { this.supportedAnnotations = Arrays.asList(supportedAnnotations); this.ignoredAnnotations = Collections.unmodifiableSet(ignoredAnnotations); } @@ -43,17 +41,17 @@ public void build(Class type, AnnotationCache cache) { visitSuperclasses(type, cache, pool); visitOuterClasses(type, cache, pool); visitPackage(type, cache, pool); - } catch (IllegalStateException ignored) { + } + catch (IllegalStateException ignored) { // Just ignore this class if it can't be processed. } } private void visitType( - Set> types, - AnnotationCache cache, - TypeDescription typeDescription, - boolean inheriting - ) { + Set> types, + AnnotationCache cache, + TypeDescription typeDescription, + boolean inheriting) { visitClass(types, cache, typeDescription, inheriting); visitFields(types, cache, typeDescription, inheriting); } @@ -86,32 +84,30 @@ private void visitPackage(Class type, AnnotationCache cache, TypePool pool) { try { TypeDescription typeDescription = pool.describe(className).resolve(); visitType(setOf(type), cache, typeDescription, false); - } catch (IllegalStateException e) { + } + catch (IllegalStateException e) { // No package object; do nothing. } } private void visitClass( - Set> types, - AnnotationCache cache, - TypeDescription typeDescription, - boolean inheriting - ) { + Set> types, + AnnotationCache cache, + TypeDescription typeDescription, + boolean inheriting) { Consumer addToCache = a -> types.forEach(t -> cache.addClassAnnotation(t, a)); typeDescription - .getDeclaredAnnotations() - .forEach(a -> cacheSupportedAnnotations(a, types, cache, addToCache, inheriting)); + .getDeclaredAnnotations() + .forEach(a -> cacheSupportedAnnotations(a, types, cache, addToCache, inheriting)); } private void visitFields( - Set> types, - AnnotationCache cache, - TypeDescription typeDescription, - boolean inheriting - ) { + Set> types, + AnnotationCache cache, + TypeDescription typeDescription, + boolean inheriting) { for (FieldDescription.InDefinedShape f : typeDescription.getDeclaredFields()) { - Consumer addToCache = a -> - types.forEach(t -> cache.addFieldAnnotation(t, f.getName(), a)); + Consumer addToCache = a -> types.forEach(t -> cache.addFieldAnnotation(t, f.getName(), a)); // Regular field annotations for (AnnotationDescription a : f.getDeclaredAnnotations()) { @@ -126,14 +122,13 @@ private void visitFields( // Getter method annotations MethodList methods = typeDescription - .getDeclaredMethods() - .filter(m -> m.getName().startsWith("get") && m.getName().length() > 3); + .getDeclaredMethods() + .filter(m -> m.getName().startsWith("get") && m.getName().length() > 3); for (MethodDescription.InDefinedShape m : methods) { String methodName = m.getName(); - String correspondingFieldName = - Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4); - Consumer addToCache = a -> - types.forEach(t -> cache.addFieldAnnotation(t, correspondingFieldName, a)); + String correspondingFieldName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4); + Consumer addToCache = + a -> types.forEach(t -> cache.addFieldAnnotation(t, correspondingFieldName, a)); for (AnnotationDescription a : m.getDeclaredAnnotations()) { cacheSupportedAnnotations(a, types, cache, addToCache, inheriting); @@ -142,12 +137,11 @@ private void visitFields( } private void cacheSupportedAnnotations( - AnnotationDescription annotation, - Set> types, - AnnotationCache cache, - Consumer addToCache, - boolean inheriting - ) { + AnnotationDescription annotation, + Set> types, + AnnotationCache cache, + Consumer addToCache, + boolean inheriting) { if (ignoredAnnotations.contains(annotation.getAnnotationType().getCanonicalName())) { return; } @@ -156,11 +150,11 @@ private void cacheSupportedAnnotations( AnnotationProperties props = buildAnnotationProperties(annotation); supportedAnnotations - .stream() - .filter(sa -> matches(annotation, sa)) - .filter(sa -> !inheriting || sa.inherits()) - .filter(sa -> sa.validate(props, cache, ignoredAnnotations)) - .forEach(addToCache.andThen(postProcess)); + .stream() + .filter(sa -> matches(annotation, sa)) + .filter(sa -> !inheriting || sa.inherits()) + .filter(sa -> sa.validate(props, cache, ignoredAnnotations)) + .forEach(addToCache.andThen(postProcess)); } private boolean matches(AnnotationDescription foundAnnotation, Annotation supportedAnnotation) { @@ -172,12 +166,8 @@ private boolean matches(AnnotationDescription foundAnnotation, Annotation suppor } private AnnotationProperties buildAnnotationProperties(AnnotationDescription annotation) { - AnnotationProperties props = new AnnotationProperties( - annotation.getAnnotationType().getCanonicalName() - ); - for (MethodDescription.InDefinedShape m : annotation - .getAnnotationType() - .getDeclaredMethods()) { + AnnotationProperties props = new AnnotationProperties(annotation.getAnnotationType().getCanonicalName()); + for (MethodDescription.InDefinedShape m : annotation.getAnnotationType().getDeclaredMethods()) { Object val = annotation.getValue(m).resolve(); String name = m.getName(); @@ -201,7 +191,8 @@ private void addArrayProperties(Object val, String name, AnnotationProperties pr for (Object obj : array) { if (obj instanceof TypeDescription) { values.add(((TypeDescription) obj).getName()); - } else { + } + else { values.add(obj.toString()); } } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/annotations/AnnotationClassCache.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/annotations/AnnotationClassCache.java index a1ba0005d..cf6df9db8 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/annotations/AnnotationClassCache.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/annotations/AnnotationClassCache.java @@ -17,10 +17,7 @@ public boolean hasClassAnnotation(Annotation annotation) { } public boolean hasFieldAnnotation(String fieldName, Annotation annotation) { - return ( - fieldAnnotations.containsKey(fieldName) && - fieldAnnotations.get(fieldName).contains(annotation) - ); + return fieldAnnotations.containsKey(fieldName) && fieldAnnotations.get(fieldName).contains(annotation); } public void addClassAnnotation(Annotation annotation) { diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/annotations/AnnotationProperties.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/annotations/AnnotationProperties.java index 50e9c1314..085a04069 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/annotations/AnnotationProperties.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/annotations/AnnotationProperties.java @@ -7,8 +7,9 @@ /** * Contains all properties of an annotation necessary to to make decisions about that annotation. * - *

Note that this object does not contain all possible properties; only the ones that are - * actually used by EqualsVerifier. + *

+ * Note that this object does not contain all possible properties; only the ones that are actually used by + * EqualsVerifier. */ public class AnnotationProperties { @@ -33,7 +34,7 @@ public String getClassName() { /** * Adds the content of an enum value property. * - * @param name The name of the enum value property. + * @param name The name of the enum value property. * @param value The content of the enum value property. */ public void putEnumValue(String name, String value) { @@ -53,7 +54,7 @@ public String getEnumValue(String name) { /** * Adds the content of an array value property. * - * @param name The name of the array value property. + * @param name The name of the array value property. * @param values The content of the array value property. */ public void putArrayValues(String name, Set values) { diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/annotations/SupportedAnnotations.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/annotations/SupportedAnnotations.java index d9e368b72..4148769cc 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/annotations/SupportedAnnotations.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/reflection/annotations/SupportedAnnotations.java @@ -6,25 +6,25 @@ import java.util.Collections; import java.util.HashSet; import java.util.Set; + import nl.jqno.equalsverifier.Warning; /** * Descriptions of the annotations that EqualsVerifier supports. * - *

The actual annotations cannot be referenced here, as that would create dependencies on the - * libraries that contain them, and it would preclude people from creating and using their own - * annotations with the same name. + *

+ * The actual annotations cannot be referenced here, as that would create dependencies on the libraries that contain + * them, and it would preclude people from creating and using their own annotations with the same name. */ public enum SupportedAnnotations implements Annotation { /** - * If a class is marked @Immutable, EqualsVerifier will not complain about fields not being - * final. + * If a class is marked @Immutable, EqualsVerifier will not complain about fields not being final. */ IMMUTABLE(false, "Immutable"), /** - * If a field is marked @Nonnull (or @NonNull or @NotNull), EqualsVerifier will not complain - * about potential {@link NullPointerException}s being thrown if this field is null. + * If a field is marked @Nonnull (or @NonNull or @NotNull), EqualsVerifier will not complain about potential + * {@link NullPointerException}s being thrown if this field is null. */ NONNULL(true, "Nonnull", "NonNull", "NotNull"), @@ -32,24 +32,19 @@ public enum SupportedAnnotations implements Annotation { NULLABLE(false, "Nullable", "CheckForNull"), /** - * If a class or package is marked with @DefaultAnnotation(Nonnull.class), EqualsVerifier will - * not complain about potential {@link NullPointerException}s being thrown if any of the fields - * in that class or package are null. + * If a class or package is marked with @DefaultAnnotation(Nonnull.class), EqualsVerifier will not complain about + * potential {@link NullPointerException}s being thrown if any of the fields in that class or package are null. * - *

Note that @DefaultAnnotation is deprecated. Nevertheless, EqualsVerifier still supports - * it. + *

+ * Note that @DefaultAnnotation is deprecated. Nevertheless, EqualsVerifier still supports it. */ - FINDBUGS1X_DEFAULT_ANNOTATION_NONNULL( - false, - "edu.umd.cs.findbugs.annotations.DefaultAnnotation", - "edu.umd.cs.findbugs.annotations.DefaultAnnotationForFields" - ) { + FINDBUGS1X_DEFAULT_ANNOTATION_NONNULL(false, "edu.umd.cs.findbugs.annotations.DefaultAnnotation", + "edu.umd.cs.findbugs.annotations.DefaultAnnotationForFields") { @Override public boolean validate( - AnnotationProperties properties, - AnnotationCache annotationCache, - Set ignoredAnnotations - ) { + AnnotationProperties properties, + AnnotationCache annotationCache, + Set ignoredAnnotations) { Set values = properties.getArrayValues("value"); for (String value : values) { for (String className : NONNULL.partialClassNames()) { @@ -63,77 +58,63 @@ public boolean validate( }, /** - * Represents any annotation that is marked with @Nonnull and @TypeQualifierDefault. If a class - * or package is marked with such an annotation, EqualsVerifier will not complain about - * potential {@link NullPointerException}s being thrown if any of the fields in that class or - * package are null. + * Represents any annotation that is marked with @Nonnull and @TypeQualifierDefault. If a class or package is marked + * with such an annotation, EqualsVerifier will not complain about potential {@link NullPointerException}s being + * thrown if any of the fields in that class or package are null. */ JSR305_DEFAULT_ANNOTATION_NONNULL(false, "") { @Override public boolean validate( - AnnotationProperties properties, - AnnotationCache annotationCache, - Set ignoredAnnotations - ) { + AnnotationProperties properties, + AnnotationCache annotationCache, + Set ignoredAnnotations) { try { Class annotationType = classForName(properties.getClassName()); if (annotationType == null) { return false; } - AnnotationCacheBuilder builder = new AnnotationCacheBuilder( - new Annotation[] { NONNULL, JSR305_TYPE_QUALIFIER_DEFAULT }, - ignoredAnnotations - ); + AnnotationCacheBuilder builder = + new AnnotationCacheBuilder(new Annotation[] { NONNULL, JSR305_TYPE_QUALIFIER_DEFAULT }, + ignoredAnnotations); builder.build(annotationType, annotationCache); - boolean hasNonnullAnnotation = annotationCache.hasClassAnnotation( - annotationType, - NONNULL - ); - boolean hasValidTypeQualifierDefault = annotationCache.hasClassAnnotation( - annotationType, - JSR305_TYPE_QUALIFIER_DEFAULT - ); + boolean hasNonnullAnnotation = annotationCache.hasClassAnnotation(annotationType, NONNULL); + boolean hasValidTypeQualifierDefault = + annotationCache.hasClassAnnotation(annotationType, JSR305_TYPE_QUALIFIER_DEFAULT); return hasNonnullAnnotation && hasValidTypeQualifierDefault; - } catch (UnsupportedClassVersionError ignored) { + } + catch (UnsupportedClassVersionError ignored) { return false; } } }, /** - * If an annotation type is marked with JSR305's @TypeQualifierDefault annotation, it becomes a - * 'default' annotation for whatever other annotation it is marked with; for example @Nonnull. + * If an annotation type is marked with JSR305's @TypeQualifierDefault annotation, it becomes a 'default' annotation + * for whatever other annotation it is marked with; for example @Nonnull. */ JSR305_TYPE_QUALIFIER_DEFAULT(false, "javax.annotation.meta.TypeQualifierDefault") { @Override public boolean validate( - AnnotationProperties properties, - AnnotationCache annotationCache, - Set ignoredAnnotations - ) { + AnnotationProperties properties, + AnnotationCache annotationCache, + Set ignoredAnnotations) { Set value = properties.getArrayValues("value"); return value.contains("FIELD") || value.contains("PARAMETER"); } }, /** - * If a class or package is marked with @NonNullByDefault or @NullMarked, EqualsVerifier will - * not complain about potential {@link NullPointerException}s being thrown if any of the fields - * in that class or package are null. + * If a class or package is marked with @NonNullByDefault or @NullMarked, EqualsVerifier will not complain about + * potential {@link NullPointerException}s being thrown if any of the fields in that class or package are null. */ - DEFAULT_ANNOTATION_NONNULL( - false, - "org.eclipse.jdt.annotation.NonNullByDefault", - "org.jspecify.annotations.NullMarked", - "org.springframework.lang.NonNullFields" - ) { + DEFAULT_ANNOTATION_NONNULL(false, "org.eclipse.jdt.annotation.NonNullByDefault", + "org.jspecify.annotations.NullMarked", "org.springframework.lang.NonNullFields") { @Override public boolean validate( - AnnotationProperties properties, - AnnotationCache annotationCache, - Set ignoredAnnotations - ) { + AnnotationProperties properties, + AnnotationCache annotationCache, + Set ignoredAnnotations) { if (properties.getClassName().endsWith("NullMarked")) { return true; } @@ -151,38 +132,25 @@ public boolean validate( }, /** - * JPA Entities cannot be final, nor can their fields be. EqualsVerifier will not complain about - * non-final fields on @Entity, @Embeddable and @MappedSuperclass classes. + * JPA Entities cannot be final, nor can their fields be. EqualsVerifier will not complain about non-final fields + * on @Entity, @Embeddable and @MappedSuperclass classes. */ - ENTITY( - false, - "javax.persistence.Entity", - "javax.persistence.Embeddable", - "javax.persistence.MappedSuperclass", - "jakarta.persistence.Entity", - "jakarta.persistence.Embeddable", - "jakarta.persistence.MappedSuperclass" - ), + ENTITY(false, "javax.persistence.Entity", "javax.persistence.Embeddable", "javax.persistence.MappedSuperclass", + "jakarta.persistence.Entity", "jakarta.persistence.Embeddable", "jakarta.persistence.MappedSuperclass"), /** - * Fields in JPA Entities that are marked @Transient should not be included in the - * equals/hashCode contract, like fields that have the Java transient modifier. EqualsVerifier - * will treat these the same. + * Fields in JPA Entities that are marked @Transient should not be included in the equals/hashCode contract, like + * fields that have the Java transient modifier. EqualsVerifier will treat these the same. */ TRANSIENT(true, "javax.persistence.Transient", "jakarta.persistence.Transient"), /** - * Fields in JPA Entities that are marked @Id or @EmbeddedId are usually part of the entity's - * surrogate key. EqualsVerifier will therefore assume that it must not be used in the - * equals/hashCode contract, unless {@link Warning#SURROGATE_KEY} is suppressed. + * Fields in JPA Entities that are marked @Id or @EmbeddedId are usually part of the entity's surrogate key. + * EqualsVerifier will therefore assume that it must not be used in the equals/hashCode contract, unless + * {@link Warning#SURROGATE_KEY} is suppressed. */ - ID( - true, - "javax.persistence.Id", - "javax.persistence.EmbeddedId", - "jakarta.persistence.Id", - "jakarta.persistence.EmbeddedId" - ) { + ID(true, "javax.persistence.Id", "javax.persistence.EmbeddedId", "jakarta.persistence.Id", + "jakarta.persistence.EmbeddedId") { @Override public void postProcess(Set> types, AnnotationCache annotationCache) { types.forEach(t -> annotationCache.addClassAnnotation(t, ID)); @@ -190,10 +158,9 @@ public void postProcess(Set> types, AnnotationCache annotationCache) { }, /** - * Fields in JPA Entities that are marked @NaturalId are part of the entity's natural/business - * identity. If a @NaturalId annotation is present in an entity, all fields marked with this - * annotation must be part of the equals/hashCode contract, and all fields NOT marked with it - * must NOT be part of the contract. + * Fields in JPA Entities that are marked @NaturalId are part of the entity's natural/business identity. If + * a @NaturalId annotation is present in an entity, all fields marked with this annotation must be part of the + * equals/hashCode contract, and all fields NOT marked with it must NOT be part of the contract. */ NATURALID(false, "org.hibernate.annotations.NaturalId") { @Override @@ -203,40 +170,28 @@ public void postProcess(Set> types, AnnotationCache annotationCache) { }, /** - * Fields in JPA entities that link to another entity, usually do so lazily. This means that - * these fields only get initialized when the getter is called; otherwise they remain null even - * if they have an underlying value. Therefore, equals and hashCode should access these fields - * through their getters, and not directly. + * Fields in JPA entities that link to another entity, usually do so lazily. This means that these fields only get + * initialized when the getter is called; otherwise they remain null even if they have an underlying value. + * Therefore, equals and hashCode should access these fields through their getters, and not directly. */ - JPA_LINKED_FIELD( - true, - "javax.persistence.OneToOne", - "javax.persistence.OneToMany", - "javax.persistence.ManyToOne", - "javax.persistence.ManyToMany", - "javax.persistence.ElementCollection", - "javax.persistence.GeneratedValue", - "jakarta.persistence.OneToOne", - "jakarta.persistence.OneToMany", - "jakarta.persistence.ManyToOne", - "jakarta.persistence.ManyToMany", - "jakarta.persistence.ElementCollection", - "jakarta.persistence.GeneratedValue" - ), + JPA_LINKED_FIELD(true, "javax.persistence.OneToOne", "javax.persistence.OneToMany", "javax.persistence.ManyToOne", + "javax.persistence.ManyToMany", "javax.persistence.ElementCollection", "javax.persistence.GeneratedValue", + "jakarta.persistence.OneToOne", "jakarta.persistence.OneToMany", "jakarta.persistence.ManyToOne", + "jakarta.persistence.ManyToMany", "jakarta.persistence.ElementCollection", + "jakarta.persistence.GeneratedValue"), /** - * Fields in JPA entities that are marked @Basic(fetch = FetchType.LAZY) are initialized lazily. - * This means that these fields only get initialized when the getter is called; otherwise they - * remain null even if they have an underlying value. Therefore, equals and hashCode should - * access these fields through their getters, and not directly. + * Fields in JPA entities that are marked @Basic(fetch = FetchType.LAZY) are initialized lazily. This means that + * these fields only get initialized when the getter is called; otherwise they remain null even if they have an + * underlying value. Therefore, equals and hashCode should access these fields through their getters, and not + * directly. */ JPA_LAZY_FIELD(true, "javax.persistence.Basic", "jakarta.persistence.Basic") { @Override public boolean validate( - AnnotationProperties properties, - AnnotationCache annotationCache, - Set ignoredAnnotations - ) { + AnnotationProperties properties, + AnnotationCache annotationCache, + Set ignoredAnnotations) { return "LAZY".equals(properties.getEnumValue("fetch")); } }; diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/testhelpers/ExpectedException.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/testhelpers/ExpectedException.java index 2749f0320..36ad8c2ba 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/testhelpers/ExpectedException.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/testhelpers/ExpectedException.java @@ -3,10 +3,7 @@ import nl.jqno.equalsverifier.internal.SuppressFBWarnings; import nl.jqno.equalsverifier.internal.exceptions.MessagingException; -@SuppressFBWarnings( - value = "NM_CLASS_NOT_EXCEPTION", - justification = "Only called in test code, not production." -) +@SuppressFBWarnings(value = "NM_CLASS_NOT_EXCEPTION", justification = "Only called in test code, not production.") public final class ExpectedException { private final Throwable e; @@ -19,7 +16,8 @@ public static ExpectedException when(Runnable runnable) { try { runnable.run(); return new ExpectedException(null); - } catch (Throwable e) { + } + catch (Throwable e) { return new ExpectedException(e); } } @@ -30,12 +28,8 @@ public ExpectedException assertThrows(Class expectedExcepti } if (!expectedException.isInstance(e)) { fail( - "Expected " + - expectedException.getCanonicalName() + - " but was " + - e.getClass().getCanonicalName() + - "." - ); + "Expected " + expectedException.getCanonicalName() + " but was " + e.getClass().getCanonicalName() + + "."); } return this; } @@ -60,11 +54,7 @@ public ExpectedException assertNotCause(Class expectedCause Throwable cause = e.getCause(); while (cause != null) { if (cause.getClass().equals(expectedCause)) { - fail( - "Expected " + - expectedCause.getSimpleName() + - " not to be in the cause but it was." - ); + fail("Expected " + expectedCause.getSimpleName() + " not to be in the cause but it was."); } cause = cause.getCause(); } @@ -113,14 +103,7 @@ public ExpectedException assertMessageContainsOnce(String fragment) { } if (occurrences != 1) { fail( - "Message [" + - e.getMessage() + - "] contains [" + - fragment + - "] " + - occurrences + - " times; should be 1." - ); + "Message [" + e.getMessage() + "] contains [" + fragment + "] " + occurrences + " times; should be 1."); } return this; } @@ -135,10 +118,7 @@ public ExpectedException assertMessageDoesNotContain(String... fragments) { return this; } - public ExpectedException assertMessageDoesNotContainAfterRemove( - String toRemove, - String... fragments - ) { + public ExpectedException assertMessageDoesNotContainAfterRemove(String toRemove, String... fragments) { String message = e.getMessage().replaceAll(toRemove, ""); for (String fragment : fragments) { if (message.contains(fragment)) { diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/testhelpers/Util.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/testhelpers/Util.java index feb7cd492..0cdc042fc 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/testhelpers/Util.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/testhelpers/Util.java @@ -3,6 +3,7 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.util.Objects; + import nl.jqno.equalsverifier.internal.SuppressFBWarnings; import nl.jqno.equalsverifier.internal.reflection.FieldIterable; import nl.jqno.equalsverifier.internal.reflection.FieldProbe; @@ -12,9 +13,8 @@ public final class Util { private Util() {} @SuppressFBWarnings( - value = "DP_DO_INSIDE_DO_PRIVILEGED", - justification = "Only called in test code, not production." - ) + value = "DP_DO_INSIDE_DO_PRIVILEGED", + justification = "Only called in test code, not production.") public static boolean defaultEquals(Object here, Object there) { Class type = here.getClass(); if (there == null || !there.getClass().isAssignableFrom(type)) { @@ -30,16 +30,16 @@ public static boolean defaultEquals(Object here, Object there) { equals &= Objects.equals(x, y); } } - } catch (IllegalAccessException e) { + } + catch (IllegalAccessException e) { throw new AssertionError(e.toString(), e); } return equals; } @SuppressFBWarnings( - value = "DP_DO_INSIDE_DO_PRIVILEGED", - justification = "Only called in test code, not production." - ) + value = "DP_DO_INSIDE_DO_PRIVILEGED", + justification = "Only called in test code, not production.") public static int defaultHashCode(Object x) { int hash = 59; try { @@ -50,7 +50,8 @@ public static int defaultHashCode(Object x) { hash += 59 * Objects.hashCode(val); } } - } catch (IllegalAccessException e) { + } + catch (IllegalAccessException e) { throw new AssertionError(e.toString(), e); } return hash; @@ -65,7 +66,8 @@ public static void coverThePrivateConstructor(Class type) { Constructor constructor = type.getDeclaredConstructor(); constructor.setAccessible(true); constructor.newInstance(); - } catch (Exception e) { + } + catch (Exception e) { throw new AssertionError("Could not call constructor of " + type.getName(), e); } } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/Assert.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/Assert.java index 25a15691b..2e4966351 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/Assert.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/Assert.java @@ -12,12 +12,12 @@ private Assert() { } /** - * Asserts that two Objects are equal to one another. Does nothing if they are; throws an - * AssertionException if they're not. + * Asserts that two Objects are equal to one another. Does nothing if they are; throws an AssertionException if + * they're not. * - * @param message Message to be included in the {@link AssertionException}. + * @param message Message to be included in the {@link AssertionException}. * @param expected Expected value. - * @param actual Actual value. + * @param actual Actual value. * @throws AssertionException If {@code expected} and {@code actual} are not equal. */ public static void assertEquals(Formatter message, Object expected, Object actual) { @@ -27,10 +27,9 @@ public static void assertEquals(Formatter message, Object expected, Object actua } /** - * Asserts that an assertion is true. Does nothing if it is; throws an AssertionException if it - * isn't. + * Asserts that an assertion is true. Does nothing if it is; throws an AssertionException if it isn't. * - * @param message Message to be included in the {@link AssertionException}. + * @param message Message to be included in the {@link AssertionException}. * @param assertion Assertion that must be true. * @throws AssertionException If {@code assertion} is false. */ @@ -41,10 +40,9 @@ public static void assertFalse(Formatter message, boolean assertion) { } /** - * Asserts that an assertion is false. Does nothing if it is; throws an AssertionException if it - * isn't. + * Asserts that an assertion is false. Does nothing if it is; throws an AssertionException if it isn't. * - * @param message Message to be included in the {@link AssertionException}. + * @param message Message to be included in the {@link AssertionException}. * @param assertion Assertion that must be true. * @throws AssertionException If {@code assertion} is false. */ @@ -68,8 +66,7 @@ public static void fail(Formatter message) { * Throws an AssertionException. * * @param message Message to be included in the {@link AssertionException}. - * @param cause Throwable to be included as cause in the {@link AssertionException}. Can be - * null. + * @param cause Throwable to be included as cause in the {@link AssertionException}. Can be null. * @throws AssertionException Always. */ public static void fail(Formatter message, Throwable cause) { diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/CachedHashCodeInitializer.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/CachedHashCodeInitializer.java index 697631262..4ebd2b342 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/CachedHashCodeInitializer.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/CachedHashCodeInitializer.java @@ -5,23 +5,26 @@ import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; + import nl.jqno.equalsverifier.internal.SuppressFBWarnings; import nl.jqno.equalsverifier.internal.reflection.FieldIterable; import nl.jqno.equalsverifier.internal.reflection.SuperclassIterable; /** - * Records an initializer for a cached hash code (field name and recompute method), if any, for the - * object to be verified. + * Records an initializer for a cached hash code (field name and recompute method), if any, for the object to be + * verified. * - *

EqualsVerifier may then, instead of calling Object.hashCode() to obtain the hash - * code, call the {@link #getInitializedHashCode(Object)} method in this class: + *

+ * EqualsVerifier may then, instead of calling Object.hashCode() to obtain the hash code, call the + * {@link #getInitializedHashCode(Object)} method in this class: * - *

* If this class has recorded a cached hash code initializer for the object, that method will - * recompute and update the cached hash code in the object automatically, before returning the - * result of Object.hashCode(). + *

+ * * If this class has recorded a cached hash code initializer for the object, that method will recompute and update the + * cached hash code in the object automatically, before returning the result of Object.hashCode(). * - *

* If this class has not recorded a cached hash code initializer for the object, it will simply - * return the value of Object.hashCode() as normal instead. + *

+ * * If this class has not recorded a cached hash code initializer for the object, it will simply return the value of + * Object.hashCode() as normal instead. */ public class CachedHashCodeInitializer { @@ -35,11 +38,10 @@ private CachedHashCodeInitializer() { } private CachedHashCodeInitializer( - boolean passthrough, - Field cachedHashCodeField, - Method calculateMethod, - T example - ) { + boolean passthrough, + Field cachedHashCodeField, + Method calculateMethod, + T example) { this.passthrough = passthrough; this.cachedHashCodeField = cachedHashCodeField; this.calculateMethod = calculateMethod; @@ -48,11 +50,10 @@ private CachedHashCodeInitializer( @SuppressFBWarnings(value = "CT_CONSTRUCTOR_THROW", justification = "Will evaluate this later") public CachedHashCodeInitializer( - Class type, - String cachedHashCodeField, - String calculateHashCodeMethod, - T example - ) { + Class type, + String cachedHashCodeField, + String calculateHashCodeMethod, + T example) { this.passthrough = false; this.cachedHashCodeField = findCachedHashCodeField(type, cachedHashCodeField); this.calculateMethod = findCalculateHashCodeMethod(type, calculateHashCodeMethod, false); @@ -66,12 +67,10 @@ public static CachedHashCodeInitializer passthrough() { public static CachedHashCodeInitializer lombokCachedHashcode(T example) { @SuppressWarnings("unchecked") final Class type = (Class) example.getClass(); - return new CachedHashCodeInitializer<>( - false, - findCachedHashCodeField(type, "$hashCodeCache"), - findCalculateHashCodeMethod(type, "hashCode", true), - example - ); + return new CachedHashCodeInitializer<>(false, + findCachedHashCodeField(type, "$hashCodeCache"), + findCalculateHashCodeMethod(type, "hashCode", true), + example); } public boolean isPassthrough() { @@ -108,45 +107,35 @@ private void recomputeCachedHashCode(Object object) { private static Field findCachedHashCodeField(Class type, String cachedHashCodeFieldName) { for (Field candidateField : FieldIterable.of(type)) { if (candidateField.getName().equals(cachedHashCodeFieldName)) { - if ( - !Modifier.isPublic(candidateField.getModifiers()) && - candidateField.getType().equals(int.class) - ) { + if (!Modifier.isPublic(candidateField.getModifiers()) && candidateField.getType().equals(int.class)) { candidateField.setAccessible(true); return candidateField; } } } - throw new IllegalArgumentException( - "Cached hashCode: Could not find cachedHashCodeField: must be 'private int " + - cachedHashCodeFieldName + - ";'" - ); + throw new IllegalArgumentException("Cached hashCode: Could not find cachedHashCodeField: must be 'private int " + + cachedHashCodeFieldName + ";'"); } private static Method findCalculateHashCodeMethod( - Class type, - String calculateHashCodeMethodName, - boolean acceptPublicMethod - ) { + Class type, + String calculateHashCodeMethodName, + boolean acceptPublicMethod) { for (Class currentClass : SuperclassIterable.ofIncludeSelf(type)) { try { Method method = currentClass.getDeclaredMethod(calculateHashCodeMethodName); - if ( - (acceptPublicMethod || !Modifier.isPublic(method.getModifiers())) && - method.getReturnType().equals(int.class) - ) { + if ((acceptPublicMethod || !Modifier.isPublic(method.getModifiers())) + && method.getReturnType().equals(int.class)) { method.setAccessible(true); return method; } - } catch (NoSuchMethodException ignore) { + } + catch (NoSuchMethodException ignore) { // Method not found; continue. } } throw new IllegalArgumentException( - "Cached hashCode: Could not find calculateHashCodeMethod: must be 'private int " + - calculateHashCodeMethodName + - "()'" - ); + "Cached hashCode: Could not find calculateHashCodeMethod: must be 'private int " + + calculateHashCodeMethodName + "()'"); } } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/Configuration.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/Configuration.java index 428a617cf..11a29bead 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/Configuration.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/Configuration.java @@ -4,6 +4,7 @@ import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Collectors; + import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.SuppressFBWarnings; import nl.jqno.equalsverifier.internal.reflection.TypeTag; @@ -11,8 +12,8 @@ public final class Configuration { - private static final Function DEFAULT_FIELDNAME_TO_GETTER_CONVERTER = fn -> - "get" + Character.toUpperCase(fn.charAt(0)) + fn.substring(1); + private static final Function DEFAULT_FIELDNAME_TO_GETTER_CONVERTER = + fn -> "get" + Character.toUpperCase(fn.charAt(0)) + fn.substring(1); private final Class type; private final Set nonnullFields; @@ -33,21 +34,20 @@ public final class Configuration { // CHECKSTYLE OFF: ParameterNumber private Configuration( - Class type, - TypeTag typeTag, - Set ignoredFields, - Set nonnullFields, - Set prefabbedFields, - AnnotationCache annotationCache, - CachedHashCodeInitializer cachedHashCodeInitializer, - boolean hasRedefinedSuperclass, - Class redefinedSubclass, - boolean usingGetClass, - EnumSet warningsToSuppress, - Function fieldnameToGetter, - List equalExamples, - List unequalExamples - ) { + Class type, + TypeTag typeTag, + Set ignoredFields, + Set nonnullFields, + Set prefabbedFields, + AnnotationCache annotationCache, + CachedHashCodeInitializer cachedHashCodeInitializer, + boolean hasRedefinedSuperclass, + Class redefinedSubclass, + boolean usingGetClass, + EnumSet warningsToSuppress, + Function fieldnameToGetter, + List equalExamples, + List unequalExamples) { this.type = type; this.typeTag = typeTag; this.ignoredFields = ignoredFields; @@ -65,22 +65,21 @@ private Configuration( } public static Configuration build( - Class type, - Set excludedFields, - Set includedFields, - Set nonnullFields, - Set prefabbedFields, - CachedHashCodeInitializer cachedHashCodeInitializer, - boolean hasRedefinedSuperclass, - Class redefinedSubclass, - boolean usingGetClass, - EnumSet warningsToSuppress, - Function fieldnameToGetter, - Set ignoredAnnotationClassNames, - Set actualFields, - List equalExamples, - List unequalExamples - ) { + Class type, + Set excludedFields, + Set includedFields, + Set nonnullFields, + Set prefabbedFields, + CachedHashCodeInitializer cachedHashCodeInitializer, + boolean hasRedefinedSuperclass, + Class redefinedSubclass, + boolean usingGetClass, + EnumSet warningsToSuppress, + Function fieldnameToGetter, + Set ignoredAnnotationClassNames, + Set actualFields, + List equalExamples, + List unequalExamples) { TypeTag typeTag = new TypeTag(type); AnnotationCache annotationCache = buildAnnotationCache(type, ignoredAnnotationClassNames); Set ignoredFields = determineIgnoredFields( @@ -89,84 +88,66 @@ public static Configuration build( warningsToSuppress, excludedFields, includedFields, - actualFields - ); - Function converter = fieldnameToGetter != null - ? fieldnameToGetter - : DEFAULT_FIELDNAME_TO_GETTER_CONVERTER; - - return new Configuration<>( - type, - typeTag, - ignoredFields, - nonnullFields, - prefabbedFields, - annotationCache, - cachedHashCodeInitializer, - hasRedefinedSuperclass, - redefinedSubclass, - usingGetClass, - warningsToSuppress, - converter, - equalExamples, - unequalExamples - ); + actualFields); + Function converter = + fieldnameToGetter != null ? fieldnameToGetter : DEFAULT_FIELDNAME_TO_GETTER_CONVERTER; + + return new Configuration<>(type, + typeTag, + ignoredFields, + nonnullFields, + prefabbedFields, + annotationCache, + cachedHashCodeInitializer, + hasRedefinedSuperclass, + redefinedSubclass, + usingGetClass, + warningsToSuppress, + converter, + equalExamples, + unequalExamples); } // CHECKSTYLE ON: ParameterNumber - private static AnnotationCache buildAnnotationCache( - Class type, - Set ignoredAnnotationClassNames - ) { - AnnotationCacheBuilder acb = new AnnotationCacheBuilder( - SupportedAnnotations.values(), - ignoredAnnotationClassNames - ); + private static AnnotationCache buildAnnotationCache(Class type, Set ignoredAnnotationClassNames) { + AnnotationCacheBuilder acb = + new AnnotationCacheBuilder(SupportedAnnotations.values(), ignoredAnnotationClassNames); AnnotationCache cache = new AnnotationCache(); acb.build(type, cache); return cache; } private static Set determineIgnoredFields( - Class type, - AnnotationCache annotationCache, - EnumSet warningsToSuppress, - Set excludedFields, - Set includedFields, - Set actualFields - ) { - BiFunction fieldHas = (f, a) -> - annotationCache.hasFieldAnnotation(type, f, a); + Class type, + AnnotationCache annotationCache, + EnumSet warningsToSuppress, + Set excludedFields, + Set includedFields, + Set actualFields) { + BiFunction fieldHas = (f, a) -> annotationCache.hasFieldAnnotation(type, f, a); if (annotationCache.hasClassAnnotation(type, SupportedAnnotations.NATURALID)) { return actualFields - .stream() - .filter(f -> !fieldHas.apply(f, SupportedAnnotations.NATURALID)) - .collect(Collectors.toSet()); + .stream() + .filter(f -> !fieldHas.apply(f, SupportedAnnotations.NATURALID)) + .collect(Collectors.toSet()); } - if ( - annotationCache.hasClassAnnotation(type, SupportedAnnotations.ID) && - !warningsToSuppress.contains(Warning.SURROGATE_OR_BUSINESS_KEY) - ) { + if (annotationCache.hasClassAnnotation(type, SupportedAnnotations.ID) + && !warningsToSuppress.contains(Warning.SURROGATE_OR_BUSINESS_KEY)) { if (warningsToSuppress.contains(Warning.SURROGATE_KEY)) { return actualFields - .stream() - .filter(f -> !fieldHas.apply(f, SupportedAnnotations.ID)) - .collect(Collectors.toSet()); - } else { + .stream() + .filter(f -> !fieldHas.apply(f, SupportedAnnotations.ID)) + .collect(Collectors.toSet()); + } + else { Set ignored = actualFields - .stream() - .filter(f -> fieldHas.apply(f, SupportedAnnotations.ID)) - .collect(Collectors.toSet()); - ignored.addAll( - determineAnnotationlessIgnoredFields( - excludedFields, - includedFields, - actualFields - ) - ); + .stream() + .filter(f -> fieldHas.apply(f, SupportedAnnotations.ID)) + .collect(Collectors.toSet()); + ignored.addAll(determineAnnotationlessIgnoredFields(excludedFields, includedFields, actualFields)); return ignored; } } @@ -174,15 +155,11 @@ private static Set determineIgnoredFields( } private static Set determineAnnotationlessIgnoredFields( - Set excludedFields, - Set includedFields, - Set actualFields - ) { + Set excludedFields, + Set includedFields, + Set actualFields) { if (!includedFields.isEmpty()) { - return actualFields - .stream() - .filter(f -> !includedFields.contains(f)) - .collect(Collectors.toSet()); + return actualFields.stream().filter(f -> !includedFields.contains(f)).collect(Collectors.toSet()); } return excludedFields; } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/Context.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/Context.java index 6081356d3..22946ddf4 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/Context.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/Context.java @@ -20,16 +20,12 @@ public final class Context { private final SubjectCreator subjectCreator; private final ValueProvider valueProvider; - @SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "FieldCache is inherently mutable" - ) + @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "FieldCache is inherently mutable") public Context( - Configuration configuration, - FactoryCache factoryCache, - FieldCache fieldCache, - Objenesis objenesis - ) { + Configuration configuration, + FactoryCache factoryCache, + FieldCache fieldCache, + Objenesis objenesis) { this.type = configuration.getType(); this.configuration = configuration; this.classProbe = new ClassProbe<>(configuration.getType()); @@ -37,8 +33,7 @@ public Context( FactoryCache cache = JavaApiPrefabValues.build().merge(factoryCache); this.valueProvider = new VintageValueProvider(cache, objenesis); - this.subjectCreator = - new SubjectCreator<>(configuration, valueProvider, fieldCache, objenesis); + this.subjectCreator = new SubjectCreator<>(configuration, valueProvider, fieldCache, objenesis); } public Class getType() { @@ -58,10 +53,7 @@ public FieldCache getFieldCache() { return fieldCache; } - @SuppressFBWarnings( - value = "EI_EXPOSE_REP", - justification = "VintageValueProvider can use a mutable cache." - ) + @SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "VintageValueProvider can use a mutable cache.") public ValueProvider getValueProvider() { return valueProvider; } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/ErrorMessage.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/ErrorMessage.java index c0abe1cd0..cbc7b9fa6 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/ErrorMessage.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/ErrorMessage.java @@ -7,18 +7,17 @@ public final class ErrorMessage { private ErrorMessage() {} private static final String WEBSITE_URL = - "For more information, go to: https://www.jqno.nl/equalsverifier/errormessages"; + "For more information, go to: https://www.jqno.nl/equalsverifier/errormessages"; public static String suffix() { return Formatter - .of( - "%%\n(EqualsVerifier %%, JDK %% running on %%, on %%)", - WEBSITE_URL, - ErrorMessage.class.getPackage().getImplementationVersion(), - System.getProperty("java.version"), - ModuleHelper.runsOnModulePath() ? "modulepath" : "classpath", - System.getProperty("os.name") - ) - .format(); + .of( + "%%\n(EqualsVerifier %%, JDK %% running on %%, on %%)", + WEBSITE_URL, + ErrorMessage.class.getPackage().getImplementationVersion(), + System.getProperty("java.version"), + ModuleHelper.runsOnModulePath() ? "modulepath" : "classpath", + System.getProperty("os.name")) + .format(); } } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/FieldNameExtractor.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/FieldNameExtractor.java index 16f2c67c1..aec32d54b 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/FieldNameExtractor.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/FieldNameExtractor.java @@ -4,6 +4,7 @@ import java.util.Collections; import java.util.HashSet; import java.util.Set; + import nl.jqno.equalsverifier.internal.reflection.FieldIterable; public final class FieldNameExtractor { diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/Formatter.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/Formatter.java index a94bf4582..8cad584bb 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/Formatter.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/Formatter.java @@ -2,15 +2,16 @@ import java.lang.reflect.Field; import java.util.regex.Matcher; + import nl.jqno.equalsverifier.internal.reflection.FieldIterable; import nl.jqno.equalsverifier.internal.reflection.FieldProbe; /** * Formats a string with the contents of one or more objects. * - *

If possible, uses each object's {@code toString} method. If this throws an exception, - * Formatter creates its own string representation of the object, containing its class name and the - * contents of its fields. + *

+ * If possible, uses each object's {@code toString} method. If this throws an exception, Formatter creates its own + * string representation of the object, containing its class name and the contents of its fields. */ public final class Formatter { @@ -29,10 +30,9 @@ private Formatter(String message, Object... objects) { /** * Factory method. * - * @param message The string that will be formatted. The substring %% represents the location - * where each object's will string representation will be inserted. - * @param objects The objects whose string representation will be inserted into the message - * string. + * @param message The string that will be formatted. The substring %% represents the location where each object's + * will string representation will be inserted. + * @param objects The objects whose string representation will be inserted into the message string. * @return A {@code Formatter}. */ public static Formatter of(String message, Object... objects) { @@ -43,8 +43,7 @@ public static Formatter of(String message, Object... objects) { * Formats the message with the given objects. * * @return The message, with the given objects's string representations inserted into it. - * @throws IllegalStateException if the number of %%'s in the message does not match the number - * of objects. + * @throws IllegalStateException if the number of %%'s in the message does not match the number of objects. */ public String format() { String result = message; @@ -67,17 +66,12 @@ private String stringify(Object obj) { } try { return obj.toString(); - } catch (AbstractMethodError e) { + } + catch (AbstractMethodError e) { return stringifyByReflection(obj); - } catch (Throwable e) { - return ( - stringifyByReflection(obj) + - "-throws " + - e.getClass().getSimpleName() + - "(" + - e.getMessage() + - ")" - ); + } + catch (Throwable e) { + return stringifyByReflection(obj) + "-throws " + e.getClass().getSimpleName() + "(" + e.getMessage() + ")"; } } diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/ListBuilders.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/ListBuilders.java index 4cdc8a48e..873ced2a0 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/ListBuilders.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/ListBuilders.java @@ -13,8 +13,8 @@ private ListBuilders() {} * Builds a list with at least one example. * * @param first The first example. - * @param more Zero or more additional examples. - * @param The type of example. + * @param more Zero or more additional examples. + * @param The type of example. * @return A list with at least one example. */ @SafeVarargs @@ -33,10 +33,10 @@ public static List buildListOfAtLeastOne(T first, T... more) { /** * Builds a list with at least two examples. * - * @param first The first example. + * @param first The first example. * @param second The second example. - * @param more Zero or more additional examples. - * @param The type of example. + * @param more Zero or more additional examples. + * @param The type of example. * @return A list with at least two examples. */ @SafeVarargs @@ -72,7 +72,7 @@ private static void addArrayElementsToList(List list, T... more) { * Builds a list from the elements of an Iterable. * * @param iterable The iterable containing the elements. - * @param The type of the elements. + * @param The type of the elements. * @return A list with the elements of the Iterable. */ public static List fromIterable(Iterable iterable) { @@ -87,7 +87,7 @@ public static List fromIterable(Iterable iterable) { * Determines whether a list contains the same example more than once. * * @param list The list that may or may not contain duplicates. - * @param The type of example. + * @param The type of example. * @return Whether the given list contains duplicates. */ public static boolean listContainsDuplicates(List list) { diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/PrimitiveMappers.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/PrimitiveMappers.java index 742c3e44c..cf1e8ec27 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/PrimitiveMappers.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/PrimitiveMappers.java @@ -9,13 +9,9 @@ public final class PrimitiveMappers { private PrimitiveMappers() {} - public static final Map, Class> PRIMITIVE_OBJECT_MAPPER = - createPrimitiveObjectMapper(); - public static final Map, Object> DEFAULT_VALUE_MAPPER = createDefaultValueMapper( - false - ); - public static final Map, Object> DEFAULT_WRAPPED_VALUE_MAPPER = - createDefaultValueMapper(true); + public static final Map, Class> PRIMITIVE_OBJECT_MAPPER = createPrimitiveObjectMapper(); + public static final Map, Object> DEFAULT_VALUE_MAPPER = createDefaultValueMapper(false); + public static final Map, Object> DEFAULT_WRAPPED_VALUE_MAPPER = createDefaultValueMapper(true); public static final Collection ZEROS = DEFAULT_WRAPPED_VALUE_MAPPER.values(); private static Map, Class> createPrimitiveObjectMapper() { diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/Rethrow.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/Rethrow.java index 1c07f2e18..74c72279d 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/Rethrow.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/Rethrow.java @@ -1,6 +1,7 @@ package nl.jqno.equalsverifier.internal.util; import java.util.function.Function; + import nl.jqno.equalsverifier.internal.exceptions.EqualsVerifierInternalBugException; import nl.jqno.equalsverifier.internal.exceptions.ModuleException; import nl.jqno.equalsverifier.internal.exceptions.ReflectionException; @@ -8,43 +9,44 @@ /** * Utilities for catching checked exceptions and re-throwing them as a RuntimeException. * - *

Java's reflection API declares lots of checked exceptions that it rarely actually throws, if - * ever. We still need to catch all of them, but the code in the catch blocks is never executed. It - * is hard to create tests to do so. Besides, EqualsVerifier contains a lot of extra checks to make - * sure these cases can never occur. + *

+ * Java's reflection API declares lots of checked exceptions that it rarely actually throws, if ever. We still need to + * catch all of them, but the code in the catch blocks is never executed. It is hard to create tests to do so. Besides, + * EqualsVerifier contains a lot of extra checks to make sure these cases can never occur. * - *

This adds a lot of noise to the test coverage and mutation coverage reports, that needs to be - * inspected manually every time. This makes me too lazy to actually do it, which is how needless - * gaps in coverage accumulate. By using Rethrow, we can easily cover the exception code, making - * gaps in coverage actual gaps in coverage that need to be dealt with instead of ignored over and - * over. + *

+ * This adds a lot of noise to the test coverage and mutation coverage reports, that needs to be inspected manually + * every time. This makes me too lazy to actually do it, which is how needless gaps in coverage accumulate. By using + * Rethrow, we can easily cover the exception code, making gaps in coverage actual gaps in coverage that need to be + * dealt with instead of ignored over and over. * - *

As a nice side effect, it makes it easier to increase the coverage threshold even more, though - * this is not the purpose of this class. + *

+ * As a nice side effect, it makes it easier to increase the coverage threshold even more, though this is not the + * purpose of this class. */ public final class Rethrow { /** Do not instantiate. */ private Rethrow() {} - public static T rethrow( - ThrowingSupplier supplier, - Function errorMessage - ) { + public static T rethrow(ThrowingSupplier supplier, Function errorMessage) { try { return supplier.get(); - } catch (RuntimeException e) { + } + catch (RuntimeException e) { if (e.getClass().getName().endsWith("InaccessibleObjectException")) { throw new ModuleException( - "The class is not accessible via the Java Module system. Consider opening the module that contains it.", - e - ); - } else { + "The class is not accessible via the Java Module system. Consider opening the module that contains it.", + e); + } + else { throw e; } - } catch (ReflectiveOperationException e) { + } + catch (ReflectiveOperationException e) { throw new ReflectionException(errorMessage.apply(e), e); - } catch (Exception e) { + } + catch (Exception e) { throw new EqualsVerifierInternalBugException(errorMessage.apply(e), e); } } @@ -54,13 +56,10 @@ public static T rethrow(ThrowingSupplier supplier) { } public static void rethrow(ThrowingRunnable block, Function errorMessage) { - rethrow( - () -> { - block.run(); - return null; - }, - errorMessage - ); + rethrow(() -> { + block.run(); + return null; + }, errorMessage); } public static void rethrow(ThrowingRunnable block) { diff --git a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/Validations.java b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/Validations.java index ece4b6740..39bc014fa 100644 --- a/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/Validations.java +++ b/equalsverifier-core/src/main/java/nl/jqno/equalsverifier/internal/util/Validations.java @@ -5,6 +5,7 @@ import java.lang.reflect.Field; import java.util.*; import java.util.stream.Collectors; + import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.instantiation.vintage.prefabvalues.factories.PrefabValueFactory; import nl.jqno.equalsverifier.internal.reflection.FieldIterable; @@ -18,49 +19,35 @@ private Validations() {} public static void validateClassCanBeVerified(Class type) { validate( ArrayList.class.isAssignableFrom(type), - "EqualsVerfifier cannot verify subclasses of java.util.ArrayList: its invariants are too complex for EqualsVerifier to maintain." - ); + "EqualsVerfifier cannot verify subclasses of java.util.ArrayList: its invariants are too complex for EqualsVerifier to maintain."); } - public static void validateFieldNamesExist( - Class type, - List givenFields, - Set actualFields - ) { + public static void validateFieldNamesExist(Class type, List givenFields, Set actualFields) { givenFields.forEach(f -> validateFieldNameExists(type, f, actualFields)); } - public static void validateFieldNameExists( - Class type, - String field, - Set actualFields - ) { + public static void validateFieldNameExists(Class type, String field, Set actualFields) { validate( !actualFields.contains(field), - "class " + type.getSimpleName() + " does not contain field " + field + "." - ); + "class " + type.getSimpleName() + " does not contain field " + field + "."); } public static void validateWarnings(Set warnings) { validate( - warnings.contains(Warning.SURROGATE_KEY) && - warnings.contains(Warning.SURROGATE_OR_BUSINESS_KEY), - "you can't suppress Warning.SURROGATE_KEY when Warning.SURROGATE_OR_BUSINESS_KEY is also suppressed." - ); + warnings.contains(Warning.SURROGATE_KEY) && warnings.contains(Warning.SURROGATE_OR_BUSINESS_KEY), + "you can't suppress Warning.SURROGATE_KEY when Warning.SURROGATE_OR_BUSINESS_KEY is also suppressed."); } public static void validateFields(Set includedFields, Set excludedFields) { validate( !includedFields.isEmpty() && !excludedFields.isEmpty(), - "you can call either withOnlyTheseFields or withIgnoredFields, but not both." - ); + "you can call either withOnlyTheseFields or withIgnoredFields, but not both."); } public static void validateNonnullFields(Set nonnullFields, Set warnings) { validate( !nonnullFields.isEmpty() && warnings.contains(Warning.NULL_FIELDS), - "you can call either withNonnullFields or suppress Warning.NULL_FIELDS, but not both." - ); + "you can call either withNonnullFields or suppress Warning.NULL_FIELDS, but not both."); } public static void validateUnequalExamples(List unequalExamples, List equalExamples) { @@ -70,88 +57,56 @@ public static void validateUnequalExamples(List unequalExamples, List } private static void validateExampleIsUnequal(T example, List equalExamples) { - validate( - equalExamples.contains(example), - "an equal example also appears as unequal example." - ); + validate(equalExamples.contains(example), "an equal example also appears as unequal example."); } public static void validateRedAndBluePrefabValues(Class type, T red, T blue) { validateNotNull(type, "prefab value type is null."); validateNotNull(red, "red prefab value of type " + type.getSimpleName() + " is null."); validateNotNull(blue, "blue prefab value of type " + type.getSimpleName() + " is null."); - validate( - red.equals(blue), - "both prefab values of type " + type.getSimpleName() + " are equal." - ); + validate(red.equals(blue), "both prefab values of type " + type.getSimpleName() + " are equal."); } - public static void validateFieldTypeMatches( - Class container, - String fieldName, - Class fieldType - ) { + public static void validateFieldTypeMatches(Class container, String fieldName, Class fieldType) { try { Field f = container.getDeclaredField(fieldName); boolean typeCompatible = f.getType().isAssignableFrom(fieldType); - boolean wrappingCompatible = fieldType.equals( - PrimitiveMappers.PRIMITIVE_OBJECT_MAPPER.get(f.getType()) - ); + boolean wrappingCompatible = fieldType.equals(PrimitiveMappers.PRIMITIVE_OBJECT_MAPPER.get(f.getType())); validate( !typeCompatible && !wrappingCompatible, - "Prefab values for field " + - fieldName + - " should be of type " + - f.getType().getSimpleName() + - " but are " + - fieldType.getSimpleName() + - "." - ); - } catch (NoSuchFieldException e) { - validate( - false, - "Class " + container.getSimpleName() + " has no field named " + fieldName + "." - ); + "Prefab values for field " + fieldName + " should be of type " + f.getType().getSimpleName() + + " but are " + fieldType.getSimpleName() + "."); + } + catch (NoSuchFieldException e) { + validate(false, "Class " + container.getSimpleName() + " has no field named " + fieldName + "."); } } - public static void validateGenericPrefabValues( - Class type, - PrefabValueFactory factory, - int arity - ) { + public static void validateGenericPrefabValues(Class type, PrefabValueFactory factory, int arity) { validateNotNull(type, "type is null."); int n = type.getTypeParameters().length; - String message = - "number of generic type parameters doesn't match:\n " + - type.getName() + - " has " + - n + - "\n Factory has " + - arity; + String message = "number of generic type parameters doesn't match:\n " + type.getName() + " has " + n + + "\n Factory has " + arity; validate(n != arity, message); } public static void validateWarningsAndFields( - Set warnings, - Set includedFields, - Set excludedFields - ) { + Set warnings, + Set includedFields, + Set excludedFields) { boolean hasSurrogateKey = warnings.contains(Warning.SURROGATE_KEY); boolean usesWithOnlyTheseFields = !includedFields.isEmpty(); boolean usesWithIgnoredFields = !excludedFields.isEmpty(); validate( hasSurrogateKey && usesWithOnlyTheseFields, - "you can't use withOnlyTheseFields when Warning.SURROGATE_KEY is suppressed.\n" + - "You can remove withOnlyTheseFields." - ); + "you can't use withOnlyTheseFields when Warning.SURROGATE_KEY is suppressed.\n" + + "You can remove withOnlyTheseFields."); validate( hasSurrogateKey && usesWithIgnoredFields, - "you can't use withIgnoredFields when Warning.SURROGATE_KEY is suppressed.\n" + - "You can remove withIgnoredFields." - ); + "you can't use withIgnoredFields when Warning.SURROGATE_KEY is suppressed.\n" + + "You can remove withIgnoredFields."); } public static void validateGivenAnnotations(Class... givenAnnotations) { @@ -159,31 +114,26 @@ public static void validateGivenAnnotations(Class... givenAnnotations) { } private static void validateIsAnnotation(Class type) { - validate( - !type.isAnnotation(), - "class " + type.getCanonicalName() + " is not an annotation." - ); + validate(!type.isAnnotation(), "class " + type.getCanonicalName() + " is not an annotation."); } public static void validateProcessedAnnotations( - Class type, - AnnotationCache cache, - Set warnings, - Set includedFields, - Set excludedFields - ) { + Class type, + AnnotationCache cache, + Set warnings, + Set includedFields, + Set excludedFields) { validateClassAnnotations(type, cache, warnings, includedFields, excludedFields); validateFieldAnnotations(type, cache, warnings, includedFields); } // CHECKSTYLE OFF: VariableDeclarationUsageDistance private static void validateClassAnnotations( - Class type, - AnnotationCache cache, - Set warnings, - Set includedFields, - Set excludedFields - ) { + Class type, + AnnotationCache cache, + Set warnings, + Set includedFields, + Set excludedFields) { boolean usesWithOnlyTheseFields = !includedFields.isEmpty(); boolean usesWithIgnoredFields = !excludedFields.isEmpty(); boolean hasNaturalId = cache.hasClassAnnotation(type, SupportedAnnotations.NATURALID); @@ -192,67 +142,51 @@ private static void validateClassAnnotations( validate( hasNaturalId && usesWithOnlyTheseFields, - "you can't use withOnlyTheseFields when fields are marked with @NaturalId." - ); + "you can't use withOnlyTheseFields when fields are marked with @NaturalId."); validate( hasNaturalId && usesWithIgnoredFields, - "you can't use withIgnoredFields when fields are marked with @NaturalId." - ); + "you can't use withIgnoredFields when fields are marked with @NaturalId."); validate( hasNaturalId && hasSurrogateKey, - "you can't suppress Warning.SURROGATE_KEY when fields are marked @NaturalId." - ); + "you can't suppress Warning.SURROGATE_KEY when fields are marked @NaturalId."); validate( hasNaturalId && hasVersionedEntity, - "you can't suppress Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY when fields are marked with @NaturalId." - ); + "you can't suppress Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY when fields are marked with @NaturalId."); } // CHECKSTYLE ON: VariableDeclarationUsageDistance private static void validateFieldAnnotations( - Class type, - AnnotationCache cache, - Set warnings, - Set includedFields - ) { - FieldIterable - .of(type) - .forEach(f -> validateFieldAnnotation(type, f, cache, warnings, includedFields)); + Class type, + AnnotationCache cache, + Set warnings, + Set includedFields) { + FieldIterable.of(type).forEach(f -> validateFieldAnnotation(type, f, cache, warnings, includedFields)); } private static void validateFieldAnnotation( - Class type, - Field f, - AnnotationCache cache, - Set warnings, - Set includedFields - ) { + Class type, + Field f, + AnnotationCache cache, + Set warnings, + Set includedFields) { validate( - includedFields.contains(f.getName()) && - cache.hasFieldAnnotation(type, f.getName(), SupportedAnnotations.ID) && - !warnings.contains(Warning.SURROGATE_OR_BUSINESS_KEY), - "you can't use withOnlyTheseFields on a field marked @Id or @EmbeddedId.\n" + - "Suppress Warning.SURROGATE_KEY and remove withOnlyTheseFields " + - "if you want to use only the @Id or @EmbeddedId fields in equals." - ); + includedFields.contains(f.getName()) + && cache.hasFieldAnnotation(type, f.getName(), SupportedAnnotations.ID) + && !warnings.contains(Warning.SURROGATE_OR_BUSINESS_KEY), + "you can't use withOnlyTheseFields on a field marked @Id or @EmbeddedId.\n" + + "Suppress Warning.SURROGATE_KEY and remove withOnlyTheseFields " + + "if you want to use only the @Id or @EmbeddedId fields in equals."); } public static void validatePackageContainsClasses(String packageName, List> types) { - validate( - types.size() == 0, - "package " + packageName + " doesn't contain any (non-Test) types." - ); + validate(types.size() == 0, "package " + packageName + " doesn't contain any (non-Test) types."); } public static void validateTypesAreKnown(List> types, List> knownTypes) { - List> unknownTypes = types - .stream() - .filter(t -> !knownTypes.contains(t)) - .collect(Collectors.toList()); - String message = - "Unknown class(es) found: " + - unknownTypes.stream().map(t -> t.getCanonicalName()).collect(Collectors.joining(", ")); + List> unknownTypes = types.stream().filter(t -> !knownTypes.contains(t)).collect(Collectors.toList()); + String message = "Unknown class(es) found: " + + unknownTypes.stream().map(t -> t.getCanonicalName()).collect(Collectors.joining(", ")); validate(!unknownTypes.isEmpty(), message); } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/CoverageNoInheritanceTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/CoverageNoInheritanceTest.java index 776643845..342d80e0f 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/CoverageNoInheritanceTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/CoverageNoInheritanceTest.java @@ -2,6 +2,7 @@ import java.lang.reflect.Constructor; import java.util.stream.Stream; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.testhelpers.types.Color; import org.junit.jupiter.params.ParameterizedTest; @@ -11,16 +12,16 @@ public class CoverageNoInheritanceTest { private static Stream data() { - return Stream.of( - Arguments.of(EclipseGetClassPoint.class), - Arguments.of(EclipseInstanceOfPoint.class), - Arguments.of(HandwrittenGetClassPoint.class), - Arguments.of(HandwrittenInstanceOfPoint.class), - Arguments.of(IntelliJGetClassPoint.class), - Arguments.of(IntelliJInstanceOfPoint.class), - Arguments.of(LombokInstanceOfPoint.class), - Arguments.of(NetBeansGetClassPoint.class) - ); + return Stream + .of( + Arguments.of(EclipseGetClassPoint.class), + Arguments.of(EclipseInstanceOfPoint.class), + Arguments.of(HandwrittenGetClassPoint.class), + Arguments.of(HandwrittenInstanceOfPoint.class), + Arguments.of(IntelliJGetClassPoint.class), + Arguments.of(IntelliJInstanceOfPoint.class), + Arguments.of(LombokInstanceOfPoint.class), + Arguments.of(NetBeansGetClassPoint.class)); } @ParameterizedTest diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/CoverageNonnullTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/CoverageNonnullTest.java index 77b4792f4..0d593207e 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/CoverageNonnullTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/CoverageNonnullTest.java @@ -11,29 +11,24 @@ public class CoverageNonnullTest { @Test public void lombokCoverage() { - EqualsVerifier - .forClass(LombokNonnullStringContainer.class) - .withIgnoredAnnotations(Nonnull.class) - .verify(); + EqualsVerifier.forClass(LombokNonnullStringContainer.class).withIgnoredAnnotations(Nonnull.class).verify(); // Also cover the constructor new LombokNonnullStringContainer(""); } /** equals and hashCode generated by Project Lombok 1.16.10, using delombok. */ - /* - * Original class: - * - * @EqualsAndHashCode - * public static final class LombokNonnullStringContainer { - * @Nonnull - * private final String s; - * - * public LombokNonnullStringContainer(String s) { - * this.s = s; - * } - * } - */ + // Original class: + // + // @EqualsAndHashCode + // public static final class LombokNonnullStringContainer { + // @Nonnull + // private final String s; + // + // public LombokNonnullStringContainer(String s) { + // this.s = s; + // } + // } public static final class LombokNonnullStringContainer { @Nonnull @@ -47,12 +42,15 @@ public LombokNonnullStringContainer(String s) { @java.lang.SuppressWarnings("all") @javax.annotation.Generated("lombok") public boolean equals(final java.lang.Object o) { - if (o == this) return true; - if (!(o instanceof CoverageNonnullTest.LombokNonnullStringContainer)) return false; + if (o == this) + return true; + if (!(o instanceof CoverageNonnullTest.LombokNonnullStringContainer)) + return false; final LombokNonnullStringContainer other = (LombokNonnullStringContainer) o; final java.lang.Object this$s = this.s; final java.lang.Object other$s = other.s; - if (this$s == null ? other$s != null : !this$s.equals(other$s)) return false; + if (this$s == null ? other$s != null : !this$s.equals(other$s)) + return false; return true; } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/CoverageWithInheritanceTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/CoverageWithInheritanceTest.java index dc4a07177..b23b1f690 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/CoverageWithInheritanceTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/CoverageWithInheritanceTest.java @@ -1,6 +1,7 @@ package nl.jqno.equalsverifier.coverage; import java.util.stream.Stream; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.testhelpers.types.Color; import org.junit.jupiter.params.ParameterizedTest; @@ -23,10 +24,10 @@ public void testSuperCoverage(Classes classes) { @MethodSource("data") public void testSubCoverage(Classes classes) { EqualsVerifier - .forClass(classes.subType) - .withRedefinedSuperclass() - .withRedefinedSubclass(classes.endpointType) - .verify(); + .forClass(classes.subType) + .withRedefinedSuperclass() + .withRedefinedSubclass(classes.endpointType) + .verify(); } @ParameterizedTest @@ -34,12 +35,8 @@ public void testSubCoverage(Classes classes) { public void callTheConstructors(Classes classes) throws Exception { classes.containerType.getConstructor().newInstance(); classes.superType.getConstructor(int.class, int.class).newInstance(0, 0); - classes.subType - .getConstructor(int.class, int.class, Color.class) - .newInstance(0, 0, Color.INDIGO); - classes.endpointType - .getConstructor(int.class, int.class, Color.class) - .newInstance(0, 0, Color.INDIGO); + classes.subType.getConstructor(int.class, int.class, Color.class).newInstance(0, 0, Color.INDIGO); + classes.endpointType.getConstructor(int.class, int.class, Color.class).newInstance(0, 0, Color.INDIGO); } private static final class Classes { @@ -50,11 +47,10 @@ private static final class Classes { private final Class endpointType; private Classes( - Class containerType, - Class superType, - Class subType, - Class endpointType - ) { + Class containerType, + Class superType, + Class subType, + Class endpointType) { this.containerType = containerType; this.superType = superType; this.subType = subType; diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/EclipseGetClassPoint.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/EclipseGetClassPoint.java index 3aa9ec92f..8d4fade64 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/EclipseGetClassPoint.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/EclipseGetClassPoint.java @@ -5,7 +5,8 @@ /** * equals and hashCode generated by Eclipse Juno. * - *

Settings: - Use 'instanceof' to compare types: false - Use blocks in 'if' statements: true + *

+ * Settings: - Use 'instanceof' to compare types: false - Use blocks in 'if' statements: true */ public final class EclipseGetClassPoint { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/EclipseInstanceOfPoint.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/EclipseInstanceOfPoint.java index 25f3c4c48..372d5d294 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/EclipseInstanceOfPoint.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/EclipseInstanceOfPoint.java @@ -5,7 +5,8 @@ /** * equals and hashCode generated by Eclipse Juno. * - *

Settings: - Use 'instanceof' to compare types: true - Use blocks in 'if' statements: true + *

+ * Settings: - Use 'instanceof' to compare types: true - Use blocks in 'if' statements: true */ public final class EclipseInstanceOfPoint { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/HandwrittenCanEqual.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/HandwrittenCanEqual.java index 68506d516..e75f37b0a 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/HandwrittenCanEqual.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/HandwrittenCanEqual.java @@ -56,11 +56,9 @@ public boolean equals(Object obj) { return false; } ColorPoint other = (ColorPoint) obj; - return ( - other.canEqual(this) && - super.equals(other) && - (color == null ? other.color == null : color.equals(other.color)) - ); + return other.canEqual(this) + && super.equals(other) + && (color == null ? other.color == null : color.equals(other.color)); } @Override diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/HandwrittenGetClassPoint.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/HandwrittenGetClassPoint.java index c34485b3d..e4963994a 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/HandwrittenGetClassPoint.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/HandwrittenGetClassPoint.java @@ -20,11 +20,7 @@ public boolean equals(Object obj) { return false; } HandwrittenGetClassPoint other = (HandwrittenGetClassPoint) obj; - return ( - x == other.x && - y == other.y && - (color == null ? other.color == null : color.equals(other.color)) - ); + return x == other.x && y == other.y && (color == null ? other.color == null : color.equals(other.color)); } @Override diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/HandwrittenInstanceOfPoint.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/HandwrittenInstanceOfPoint.java index f38fe8015..415a02ea1 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/HandwrittenInstanceOfPoint.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/HandwrittenInstanceOfPoint.java @@ -20,11 +20,7 @@ public boolean equals(Object obj) { return false; } HandwrittenInstanceOfPoint other = (HandwrittenInstanceOfPoint) obj; - return ( - x == other.x && - y == other.y && - (color == null ? other.color == null : color.equals(other.color)) - ); + return x == other.x && y == other.y && (color == null ? other.color == null : color.equals(other.color)); } @Override diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/IntelliJGetClassPoint.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/IntelliJGetClassPoint.java index 4462d75b6..b31391bee 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/IntelliJGetClassPoint.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/IntelliJGetClassPoint.java @@ -5,7 +5,8 @@ /** * equals and hashCode generated by IntelliJ IDEA 12. * - *

Settings: - Accept subclasses as parameter to equals() method: false + *

+ * Settings: - Accept subclasses as parameter to equals() method: false */ // CHECKSTYLE OFF: NeedBraces public final class IntelliJGetClassPoint { @@ -22,14 +23,19 @@ public IntelliJGetClassPoint(int x, int y, Color color) { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; IntelliJGetClassPoint point = (IntelliJGetClassPoint) o; - if (x != point.x) return false; - if (y != point.y) return false; - if (color != point.color) return false; + if (x != point.x) + return false; + if (y != point.y) + return false; + if (color != point.color) + return false; return true; } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/IntelliJInstanceOfPoint.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/IntelliJInstanceOfPoint.java index 5556511e2..d19ce4593 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/IntelliJInstanceOfPoint.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/IntelliJInstanceOfPoint.java @@ -5,7 +5,8 @@ /** * equals and hashCode generated by IntelliJ IDEA 12. * - *

Settings: - Accept subclasses as parameter to equals() method: true + *

+ * Settings: - Accept subclasses as parameter to equals() method: true */ // CHECKSTYLE OFF: NeedBraces public final class IntelliJInstanceOfPoint { @@ -22,14 +23,19 @@ public IntelliJInstanceOfPoint(int x, int y, Color color) { @Override public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof IntelliJInstanceOfPoint)) return false; + if (this == o) + return true; + if (!(o instanceof IntelliJInstanceOfPoint)) + return false; IntelliJInstanceOfPoint point = (IntelliJInstanceOfPoint) o; - if (x != point.x) return false; - if (y != point.y) return false; - if (color != point.color) return false; + if (x != point.x) + return false; + if (y != point.y) + return false; + if (color != point.color) + return false; return true; } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/LombokCanEqual.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/LombokCanEqual.java index dc7ff041a..ab576321f 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/LombokCanEqual.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/LombokCanEqual.java @@ -8,20 +8,18 @@ public class LombokCanEqual { /** equals and hashCode generated by Project Lombok 0.12, using delombok. */ - /* - * Original class: - * - * @EqualsAndHashCode - * public static class Point { - * private final int x; - * private final int y; - * - * public Point(int x, int y) { - * this.x = x; - * this.y = y; - * } - * } - */ + // Original class: + // + // @EqualsAndHashCode + // public static class Point { + // private final int x; + // private final int y; + // + // public Point(int x, int y) { + // this.x = x; + // this.y = y; + // } + // } public static class Point { private final int x; @@ -35,12 +33,17 @@ public Point(int x, int y) { @java.lang.Override @java.lang.SuppressWarnings("all") public boolean equals(final java.lang.Object o) { - if (o == this) return true; - if (!(o instanceof LombokCanEqual.Point)) return false; + if (o == this) + return true; + if (!(o instanceof LombokCanEqual.Point)) + return false; final Point other = (Point) o; - if (!other.canEqual((java.lang.Object) this)) return false; - if (this.x != other.x) return false; - if (this.y != other.y) return false; + if (!other.canEqual((java.lang.Object) this)) + return false; + if (this.x != other.x) + return false; + if (this.y != other.y) + return false; return true; } @@ -64,15 +67,9 @@ public int hashCode() { /* * Original class: * - * @EqualsAndHashCode(callSuper=true) - * public static class ColorPoint extends Point { - * private final Color color; + * @EqualsAndHashCode(callSuper=true) public static class ColorPoint extends Point { private final Color color; * - * public ColorPoint(int x, int y, Color color) { - * super(x, y); - * this.color = color; - * } - * } + * public ColorPoint(int x, int y, Color color) { super(x, y); this.color = color; } } */ public static class ColorPoint extends Point { @@ -86,16 +83,19 @@ public ColorPoint(int x, int y, Color color) { @java.lang.Override @java.lang.SuppressWarnings("all") public boolean equals(final java.lang.Object o) { - if (o == this) return true; - if (!(o instanceof LombokCanEqual.ColorPoint)) return false; + if (o == this) + return true; + if (!(o instanceof LombokCanEqual.ColorPoint)) + return false; final ColorPoint other = (ColorPoint) o; - if (!other.canEqual((java.lang.Object) this)) return false; - if (!super.equals(o)) return false; + if (!other.canEqual((java.lang.Object) this)) + return false; + if (!super.equals(o)) + return false; final java.lang.Object this$color = this.color; final java.lang.Object other$color = other.color; - if ( - this$color == null ? other$color != null : !this$color.equals(other$color) - ) return false; + if (this$color == null ? other$color != null : !this$color.equals(other$color)) + return false; return true; } @@ -119,7 +119,8 @@ public int hashCode() { /** * Handwritten leaf node to achive 100% coverage. * - *

Without this, the canEqual == false branch in ColorPoint will not be reached. + *

+ * Without this, the canEqual == false branch in ColorPoint will not be reached. */ public static final class EndPoint extends ColorPoint { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/LombokInstanceOfPoint.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/LombokInstanceOfPoint.java index 9d712ac59..f7bdcccf5 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/LombokInstanceOfPoint.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/coverage/LombokInstanceOfPoint.java @@ -3,22 +3,20 @@ import nl.jqno.equalsverifier.testhelpers.types.Color; /** equals and hashCode generated by Project Lombok 0.12, using delombok. */ -/* - * Original class: - * - * @EqualsAndHashCode - * public final class LombokInstanceOfPoint { - * private final int x; - * private final int y; - * private final Color color; - * - * public LombokInstanceOfPoint(int x, int y, Color color) { - * this.x = x; - * this.y = y; - * this.color = color; - * } - * } - */ +// Original class: +// +// @EqualsAndHashCode +// public final class LombokInstanceOfPoint { +// private final int x; +// private final int y; +// private final Color color; +// +// public LombokInstanceOfPoint(int x, int y, Color color) { +// this.x = x; +// this.y = y; +// this.color = color; +// } +// } // CHECKSTYLE OFF: LocalFinalVariableName // CHECKSTYLE OFF: NeedBraces public final class LombokInstanceOfPoint { @@ -36,16 +34,19 @@ public LombokInstanceOfPoint(int x, int y, Color color) { @java.lang.Override @java.lang.SuppressWarnings("all") public boolean equals(final java.lang.Object o) { - if (o == this) return true; - if (!(o instanceof LombokInstanceOfPoint)) return false; + if (o == this) + return true; + if (!(o instanceof LombokInstanceOfPoint)) + return false; final LombokInstanceOfPoint other = (LombokInstanceOfPoint) o; - if (this.x != other.x) return false; - if (this.y != other.y) return false; + if (this.x != other.x) + return false; + if (this.y != other.y) + return false; final java.lang.Object this$color = this.color; final java.lang.Object other$color = other.color; - if ( - this$color == null ? other$color != null : !this$color.equals(other$color) - ) return false; + if (this$color == null ? other$color != null : !this$color.equals(other$color)) + return false; return true; } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/basic_contract/HashCodeTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/basic_contract/HashCodeTest.java index 93f58fb97..c15f3c72d 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/basic_contract/HashCodeTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/basic_contract/HashCodeTest.java @@ -9,23 +9,17 @@ public class HashCodeTest { @Test public void fail_whenHashCodesAreInconsistent() { ExpectedException - .when(() -> EqualsVerifier.forClass(RandomHashCode.class).verify()) - .assertFailure() - .assertMessageContains( - "hashCode: hashCode should be consistent", - RandomHashCode.class.getSimpleName() - ); + .when(() -> EqualsVerifier.forClass(RandomHashCode.class).verify()) + .assertFailure() + .assertMessageContains("hashCode: hashCode should be consistent", RandomHashCode.class.getSimpleName()); } @Test public void fail_whenHashCodesAreUnequal_givenEqualObjects() { ExpectedException - .when(() -> EqualsVerifier.forClass(NoHashCode.class).verify()) - .assertFailure() - .assertMessageContains( - "hashCode: hashCodes should be equal", - NoHashCode.class.getSimpleName() - ); + .when(() -> EqualsVerifier.forClass(NoHashCode.class).verify()) + .assertFailure() + .assertMessageContains("hashCode: hashCodes should be equal", NoHashCode.class.getSimpleName()); } @Test diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/basic_contract/NonNullityTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/basic_contract/NonNullityTest.java index aefa88ebf..d34a722ad 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/basic_contract/NonNullityTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/basic_contract/NonNullityTest.java @@ -10,17 +10,17 @@ public class NonNullityTest { @Test public void fail_whenNullPointerExceptionIsThrown_givenNullInput() { ExpectedException - .when(() -> EqualsVerifier.forClass(NullPointerExceptionThrower.class).verify()) - .assertFailure() - .assertMessageContains("Non-nullity: NullPointerException thrown"); + .when(() -> EqualsVerifier.forClass(NullPointerExceptionThrower.class).verify()) + .assertFailure() + .assertMessageContains("Non-nullity: NullPointerException thrown"); } @Test public void fail_whenEqualsReturnsTrue_givenNullInput() { ExpectedException - .when(() -> EqualsVerifier.forClass(NullReturnsTrue.class).verify()) - .assertFailure() - .assertMessageContains("Non-nullity: true returned for null value"); + .when(() -> EqualsVerifier.forClass(NullReturnsTrue.class).verify()) + .assertFailure() + .assertMessageContains("Non-nullity: true returned for null value"); } static final class NullPointerExceptionThrower extends Point { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/basic_contract/ReflexivityTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/basic_contract/ReflexivityTest.java index 991869f89..3c992dde0 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/basic_contract/ReflexivityTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/basic_contract/ReflexivityTest.java @@ -3,6 +3,7 @@ import static nl.jqno.equalsverifier.internal.testhelpers.Util.defaultHashCode; import java.util.Objects; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; @@ -15,82 +16,71 @@ public class ReflexivityTest { @Test public void fail_whenReferencesAreNotEqual() { ExpectedException - .when(() -> EqualsVerifier.forClass(ReflexivityIntentionallyBroken.class).verify()) - .assertFailure() - .assertMessageContains( - "Reflexivity", - "object does not equal itself", - ReflexivityIntentionallyBroken.class.getSimpleName() - ); + .when(() -> EqualsVerifier.forClass(ReflexivityIntentionallyBroken.class).verify()) + .assertFailure() + .assertMessageContains( + "Reflexivity", + "object does not equal itself", + ReflexivityIntentionallyBroken.class.getSimpleName()); } @Test public void fail_whenTheWrongFieldsAreComparedInEquals() { ExpectedException - .when(() -> EqualsVerifier.forClass(FieldsMixedUpInEquals.class).verify()) - .assertFailure() - .assertMessageContains( - "Reflexivity", - "object does not equal an identical copy of itself", - FieldsMixedUpInEquals.class.getSimpleName() - ); + .when(() -> EqualsVerifier.forClass(FieldsMixedUpInEquals.class).verify()) + .assertFailure() + .assertMessageContains( + "Reflexivity", + "object does not equal an identical copy of itself", + FieldsMixedUpInEquals.class.getSimpleName()); } @Test public void fail_whenReferencesAreNotEqual_givenFieldsThatAreNull() { ExpectedException - .when(() -> EqualsVerifier.forClass(ReflexivityBrokenOnNullFields.class).verify()) - .assertFailure() - .assertMessageContains( - "Reflexivity", - ReflexivityBrokenOnNullFields.class.getSimpleName() - ); + .when(() -> EqualsVerifier.forClass(ReflexivityBrokenOnNullFields.class).verify()) + .assertFailure() + .assertMessageContains("Reflexivity", ReflexivityBrokenOnNullFields.class.getSimpleName()); } @Test public void succeed_whenReferencesAreNotEqual_givenFieldsThatAreNullAndWarningIsSuppressed() { - EqualsVerifier - .forClass(ReflexivityBrokenOnNullFields.class) - .suppress(Warning.NULL_FIELDS) - .verify(); + EqualsVerifier.forClass(ReflexivityBrokenOnNullFields.class).suppress(Warning.NULL_FIELDS).verify(); } @Test public void fail_whenObjectIsInstanceofCheckedWithWrongClass() { ExpectedException - .when(() -> EqualsVerifier.forClass(WrongInstanceofCheck.class).verify()) - .assertFailure() - .assertMessageContains( - "Reflexivity", - "object does not equal an identical copy of itself", - WrongInstanceofCheck.class.getSimpleName() - ); + .when(() -> EqualsVerifier.forClass(WrongInstanceofCheck.class).verify()) + .assertFailure() + .assertMessageContains( + "Reflexivity", + "object does not equal an identical copy of itself", + WrongInstanceofCheck.class.getSimpleName()); } @Test public void fail_whenEqualsReturnsFalse_givenObjectsThatAreIdentical() { ExpectedException - .when(() -> EqualsVerifier.forClass(SuperCallerWithUnusedField.class).verify()) - .assertFailure() - .assertMessageContains("Reflexivity", "identical copy"); + .when(() -> EqualsVerifier.forClass(SuperCallerWithUnusedField.class).verify()) + .assertFailure() + .assertMessageContains("Reflexivity", "identical copy"); } @Test public void succeed_whenEqualsReturnsFalse_givenObjectsThatAreIdenticalAndWarningIsSuppressed() { EqualsVerifier - .forClass(SuperCallerWithUnusedField.class) - .suppress(Warning.IDENTICAL_COPY, Warning.ALL_FIELDS_SHOULD_BE_USED) - .verify(); + .forClass(SuperCallerWithUnusedField.class) + .suppress(Warning.IDENTICAL_COPY, Warning.ALL_FIELDS_SHOULD_BE_USED) + .verify(); } @Test public void fail_whenIdenticalCopyWarningIsSuppressedUnnecessarily() { ExpectedException - .when(() -> - EqualsVerifier.forClass(FinalPoint.class).suppress(Warning.IDENTICAL_COPY).verify() - ) - .assertFailure() - .assertMessageContains("Unnecessary suppression", "IDENTICAL_COPY"); + .when(() -> EqualsVerifier.forClass(FinalPoint.class).suppress(Warning.IDENTICAL_COPY).verify()) + .assertFailure() + .assertMessageContains("Unnecessary suppression", "IDENTICAL_COPY"); } static final class ReflexivityIntentionallyBroken extends Point { @@ -156,15 +146,21 @@ public ReflexivityBrokenOnNullFields(Object a) { // CHECKSTYLE OFF: NeedBraces @Override public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; ReflexivityBrokenOnNullFields other = (ReflexivityBrokenOnNullFields) obj; if (a == null) { - if (other.a != null) return false; + if (other.a != null) + return false; // The following line was added to cause equals to be broken on reflexivity. return false; - } else if (!a.equals(other.a)) return false; + } + else if (!a.equals(other.a)) + return false; return true; } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/basic_contract/SymmetryTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/basic_contract/SymmetryTest.java index 863cae383..0682b8f22 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/basic_contract/SymmetryTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/basic_contract/SymmetryTest.java @@ -15,14 +15,9 @@ public class SymmetryTest { @Test public void fail_whenEqualsIsNotSymmetrical() { ExpectedException - .when(() -> EqualsVerifier.forClass(SymmetryIntentionallyBroken.class).verify()) - .assertFailure() - .assertMessageContains( - SYMMETRY, - NOT_SYMMETRIC, - AND, - SymmetryIntentionallyBroken.class.getSimpleName() - ); + .when(() -> EqualsVerifier.forClass(SymmetryIntentionallyBroken.class).verify()) + .assertFailure() + .assertMessageContains(SYMMETRY, NOT_SYMMETRIC, AND, SymmetryIntentionallyBroken.class.getSimpleName()); } static final class SymmetryIntentionallyBroken { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/basic_contract/TransitivityTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/basic_contract/TransitivityTest.java index 23510c710..b686f9c12 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/basic_contract/TransitivityTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/basic_contract/TransitivityTest.java @@ -3,6 +3,7 @@ import static nl.jqno.equalsverifier.internal.testhelpers.Util.defaultHashCode; import java.util.Objects; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; @@ -19,19 +20,16 @@ public void succeed_whenEqualityForTwoFieldsIsCombinedUsingAnd() { @Test public void fail_whenEqualityForTwoFieldsIsCombinedUsingOr() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(TwoFieldsUsingOr.class) - .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) - .verify() - ) - .assertFailure() - .assertMessageContains( - "Transitivity", - "two of these three instances are equal to each other, so the third one" + - " should be, too", - TwoFieldsUsingOr.class.getSimpleName() - ); + .when( + () -> EqualsVerifier + .forClass(TwoFieldsUsingOr.class) + .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) + .verify()) + .assertFailure() + .assertMessageContains( + "Transitivity", + "two of these three instances are equal to each other, so the third one should be, too", + TwoFieldsUsingOr.class.getSimpleName()); } @Test @@ -42,14 +40,13 @@ public void succeed_whenEqualityForThreeFieldsIsCombinedUsingAnd() { @Test public void fail_whenEqualityForThreeFieldsIsCombinedUsingOr() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(ThreeFieldsUsingOr.class) - .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) - .verify() - ) - .assertFailure() - .assertMessageContains("Transitivity"); + .when( + () -> EqualsVerifier + .forClass(ThreeFieldsUsingOr.class) + .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) + .verify()) + .assertFailure() + .assertMessageContains("Transitivity"); } @Test @@ -60,81 +57,75 @@ public void fail_whenEqualityForThreeFieldsIsCombinedUsingOr_givenRelaxedEqualEx ThreeFieldsUsingOr other = new ThreeFieldsUsingOr("d", "4", "delta"); ExpectedException - .when(() -> - EqualsVerifier - .forRelaxedEqualExamples(one, two, three) - .andUnequalExample(other) - .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) - .verify() - ) - .assertFailure() - .assertMessageContains("Transitivity"); + .when( + () -> EqualsVerifier + .forRelaxedEqualExamples(one, two, three) + .andUnequalExample(other) + .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) + .verify()) + .assertFailure() + .assertMessageContains("Transitivity"); } @Test public void fail_whenEqualityForThreeFieldsIsCombinedUsingAndAndOr() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(ThreeFieldsUsingAndOr.class) - .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) - .verify() - ) - .assertFailure() - .assertMessageContains("Transitivity"); + .when( + () -> EqualsVerifier + .forClass(ThreeFieldsUsingAndOr.class) + .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) + .verify()) + .assertFailure() + .assertMessageContains("Transitivity"); } @Test public void fail_whenEqualityForThreeFieldsIsCombinedUsingOrAndAnd() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(ThreeFieldsUsingOrAnd.class) - .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) - .verify() - ) - .assertFailure() - .assertMessageContains("Transitivity"); + .when( + () -> EqualsVerifier + .forClass(ThreeFieldsUsingOrAnd.class) + .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) + .verify()) + .assertFailure() + .assertMessageContains("Transitivity"); } @Test public void fail_whenEqualityForFiveFieldsIsCombinedUsingOr() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(FiveFieldsUsingOr.class) - .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) - .verify() - ) - .assertFailure() - .assertMessageContains("Transitivity"); + .when( + () -> EqualsVerifier + .forClass(FiveFieldsUsingOr.class) + .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) + .verify()) + .assertFailure() + .assertMessageContains("Transitivity"); } @Test public void fail_whenEqualityForFiveFieldsIsCombinedUsingAndsAndOrs() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(FiveFieldsUsingAndsAndOrs.class) - .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) - .verify() - ) - .assertFailure() - .assertMessageContains("Transitivity"); + .when( + () -> EqualsVerifier + .forClass(FiveFieldsUsingAndsAndOrs.class) + .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) + .verify()) + .assertFailure() + .assertMessageContains("Transitivity"); } @Disabled("This class is not transitive, and it should fail. See issue 78.") @Test public void fail_whenInstancesAreEqualIfAtLeastTwoFieldsAreEqual() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(AtLeast2FieldsAreEqual.class) - .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) - .verify() - ) - .assertFailure() - .assertMessageContains("Transitivity"); + .when( + () -> EqualsVerifier + .forClass(AtLeast2FieldsAreEqual.class) + .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) + .verify()) + .assertFailure() + .assertMessageContains("Transitivity"); } static final class TwoFieldsUsingAnd { @@ -205,11 +196,7 @@ public boolean equals(Object obj) { return false; } ThreeFieldsUsingAnd other = (ThreeFieldsUsingAnd) obj; - return ( - Objects.equals(f, other.f) && - Objects.equals(g, other.g) && - Objects.equals(h, other.h) - ); + return Objects.equals(f, other.f) && Objects.equals(g, other.g) && Objects.equals(h, other.h); } @Override @@ -236,11 +223,7 @@ public boolean equals(Object obj) { return false; } ThreeFieldsUsingOr other = (ThreeFieldsUsingOr) obj; - return ( - Objects.equals(f, other.f) || - Objects.equals(g, other.g) || - Objects.equals(h, other.h) - ); + return Objects.equals(f, other.f) || Objects.equals(g, other.g) || Objects.equals(h, other.h); } @Override @@ -267,10 +250,7 @@ public boolean equals(Object obj) { return false; } ThreeFieldsUsingAndOr other = (ThreeFieldsUsingAndOr) obj; - return ( - (Objects.equals(f, other.f) && Objects.equals(g, other.g)) || - Objects.equals(h, other.h) - ); + return (Objects.equals(f, other.f) && Objects.equals(g, other.g) || Objects.equals(h, other.h)); } @Override @@ -297,10 +277,7 @@ public boolean equals(Object obj) { return false; } ThreeFieldsUsingOrAnd other = (ThreeFieldsUsingOrAnd) obj; - return ( - Objects.equals(f, other.f) || - (Objects.equals(g, other.g) && Objects.equals(h, other.h)) - ); + return Objects.equals(f, other.f) || (Objects.equals(g, other.g) && Objects.equals(h, other.h)); } @Override @@ -331,13 +308,11 @@ public boolean equals(Object obj) { return false; } FiveFieldsUsingOr other = (FiveFieldsUsingOr) obj; - return ( - Objects.equals(f, other.f) || - Objects.equals(g, other.g) || - Objects.equals(h, other.h) || - Objects.equals(i, other.i) || - Objects.equals(j, other.j) - ); + return Objects.equals(f, other.f) + || Objects.equals(g, other.g) + || Objects.equals(h, other.h) + || Objects.equals(i, other.i) + || Objects.equals(j, other.j); } @Override @@ -368,11 +343,9 @@ public boolean equals(Object obj) { return false; } FiveFieldsUsingAndsAndOrs other = (FiveFieldsUsingAndsAndOrs) obj; - return ( - Objects.equals(f, other.f) || - (Objects.equals(g, other.g) && Objects.equals(h, other.h)) || - (Objects.equals(i, other.i) && Objects.equals(j, other.j)) - ); + return Objects.equals(f, other.f) + || (Objects.equals(g, other.g) && Objects.equals(h, other.h)) + || (Objects.equals(i, other.i) && Objects.equals(j, other.j)); } @Override diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/AbstractDelegationTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/AbstractDelegationTest.java index b816c5d82..eb14304d3 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/AbstractDelegationTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/AbstractDelegationTest.java @@ -4,6 +4,7 @@ import static nl.jqno.equalsverifier.internal.testhelpers.Util.defaultHashCode; import java.util.Objects; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; import org.junit.jupiter.api.Test; @@ -13,8 +14,7 @@ public class AbstractDelegationTest { private static final String ABSTRACT_DELEGATION = "Abstract delegation"; private static final String EQUALS_DELEGATES = "equals method delegates to an abstract method"; - private static final String HASHCODE_DELEGATES = - "hashCode method delegates to an abstract method"; + private static final String HASHCODE_DELEGATES = "hashCode method delegates to an abstract method"; private static final String PREFAB = "Add prefab values for"; @Test @@ -25,27 +25,25 @@ public void succeed_whenClassHasAFieldOfAnAbstractClass() { @Test public void failGracefully_whenEqualsCallsAnAbstractMethod() { ExpectedException - .when(() -> EqualsVerifier.forClass(AbstractEqualsDelegator.class).verify()) - .assertFailure() - .assertCause(AbstractMethodError.class) - .assertMessageContains( - ABSTRACT_DELEGATION, - EQUALS_DELEGATES, - AbstractEqualsDelegator.class.getSimpleName() - ); + .when(() -> EqualsVerifier.forClass(AbstractEqualsDelegator.class).verify()) + .assertFailure() + .assertCause(AbstractMethodError.class) + .assertMessageContains( + ABSTRACT_DELEGATION, + EQUALS_DELEGATES, + AbstractEqualsDelegator.class.getSimpleName()); } @Test public void failGracefully_whenHashCodeCallsAnAbstractMethod() { ExpectedException - .when(() -> EqualsVerifier.forClass(AbstractHashCodeDelegator.class).verify()) - .assertFailure() - .assertCause(AbstractMethodError.class) - .assertMessageContains( - ABSTRACT_DELEGATION, - HASHCODE_DELEGATES, - AbstractHashCodeDelegator.class.getSimpleName() - ); + .when(() -> EqualsVerifier.forClass(AbstractHashCodeDelegator.class).verify()) + .assertFailure() + .assertCause(AbstractMethodError.class) + .assertMessageContains( + ABSTRACT_DELEGATION, + HASHCODE_DELEGATES, + AbstractHashCodeDelegator.class.getSimpleName()); } @Test @@ -56,55 +54,41 @@ public void succeed_whenToStringCallsAnAbstractMethod() { @Test public void failGracefully_whenEqualsCallsAnAbstractFieldsAbstractMethod() { ExpectedException - .when(() -> - EqualsVerifier.forClass(EqualsDelegatesToAbstractMethodInField.class).verify() - ) - .assertFailure() - .assertCause(AbstractMethodError.class) - .assertMessageContains( - ABSTRACT_DELEGATION, - EQUALS_DELEGATES, - EqualsDelegatesToAbstractMethodInField.class.getSimpleName() - ); + .when(() -> EqualsVerifier.forClass(EqualsDelegatesToAbstractMethodInField.class).verify()) + .assertFailure() + .assertCause(AbstractMethodError.class) + .assertMessageContains( + ABSTRACT_DELEGATION, + EQUALS_DELEGATES, + EqualsDelegatesToAbstractMethodInField.class.getSimpleName()); } @Test public void succeed_whenEqualsCallsAnAbstractFieldsAbstactMethod_givenAConcretePrefabImplementationOfSaidAbstractField() { EqualsVerifier - .forClass(EqualsDelegatesToAbstractMethodInField.class) - .withPrefabValues( - AbstractDelegator.class, - new AbstractDelegatorImpl(1), - new AbstractDelegatorImpl(2) - ) - .verify(); + .forClass(EqualsDelegatesToAbstractMethodInField.class) + .withPrefabValues(AbstractDelegator.class, new AbstractDelegatorImpl(1), new AbstractDelegatorImpl(2)) + .verify(); } @Test public void failGracefully_whenHashCodeCallsAnAbstractFieldsAbstactMethod() { ExpectedException - .when(() -> - EqualsVerifier.forClass(HashCodeDelegatesToAbstractMethodInField.class).verify() - ) - .assertFailure() - .assertCause(AbstractMethodError.class) - .assertMessageContains( - ABSTRACT_DELEGATION, - HASHCODE_DELEGATES, - HashCodeDelegatesToAbstractMethodInField.class.getSimpleName() - ); + .when(() -> EqualsVerifier.forClass(HashCodeDelegatesToAbstractMethodInField.class).verify()) + .assertFailure() + .assertCause(AbstractMethodError.class) + .assertMessageContains( + ABSTRACT_DELEGATION, + HASHCODE_DELEGATES, + HashCodeDelegatesToAbstractMethodInField.class.getSimpleName()); } @Test public void succeed_whenHashCodeCallsAnAbstractFieldsAbstactMethod_givenAConcretePrefabImplementationOfSaidAbstractField() { EqualsVerifier - .forClass(HashCodeDelegatesToAbstractMethodInField.class) - .withPrefabValues( - AbstractDelegator.class, - new AbstractDelegatorImpl(1), - new AbstractDelegatorImpl(2) - ) - .verify(); + .forClass(HashCodeDelegatesToAbstractMethodInField.class) + .withPrefabValues(AbstractDelegator.class, new AbstractDelegatorImpl(1), new AbstractDelegatorImpl(2)) + .verify(); } @Test @@ -115,57 +99,49 @@ public void succeed_whenToStringCallsAnAbstractFieldsAbstractMethod() { @Test public void failGracefully_whenAFieldsEqualsMethodCallsAnAbstractField() { ExpectedException - .when(() -> - EqualsVerifier.forClass(EqualsInFieldDelegatesToAbstractMethod.class).verify() - ) - .assertFailure() - .assertCause(AbstractMethodError.class) - .assertMessageContains( - ABSTRACT_DELEGATION, - EQUALS_DELEGATES, - PREFAB, - AbstractEqualsDelegator.class.getSimpleName() - ); + .when(() -> EqualsVerifier.forClass(EqualsInFieldDelegatesToAbstractMethod.class).verify()) + .assertFailure() + .assertCause(AbstractMethodError.class) + .assertMessageContains( + ABSTRACT_DELEGATION, + EQUALS_DELEGATES, + PREFAB, + AbstractEqualsDelegator.class.getSimpleName()); } @Test public void succeed_whenAFieldsEqualsMethodCallsAnAbstractField_givenAConcretePrefabImplementationOfSaidField() { EqualsVerifier - .forClass(EqualsInFieldDelegatesToAbstractMethod.class) - .withPrefabValues( - AbstractEqualsDelegator.class, - new AbstractEqualsDelegatorImpl(1), - new AbstractEqualsDelegatorImpl(2) - ) - .verify(); + .forClass(EqualsInFieldDelegatesToAbstractMethod.class) + .withPrefabValues( + AbstractEqualsDelegator.class, + new AbstractEqualsDelegatorImpl(1), + new AbstractEqualsDelegatorImpl(2)) + .verify(); } @Test public void failGracefully_whenAFieldsHashCodeMethodCallsAnAbstractField() { ExpectedException - .when(() -> - EqualsVerifier.forClass(HashCodeInFieldDelegatesToAbstractMethod.class).verify() - ) - .assertFailure() - .assertCause(AbstractMethodError.class) - .assertMessageContains( - ABSTRACT_DELEGATION, - HASHCODE_DELEGATES, - PREFAB, - AbstractHashCodeDelegator.class.getSimpleName() - ); + .when(() -> EqualsVerifier.forClass(HashCodeInFieldDelegatesToAbstractMethod.class).verify()) + .assertFailure() + .assertCause(AbstractMethodError.class) + .assertMessageContains( + ABSTRACT_DELEGATION, + HASHCODE_DELEGATES, + PREFAB, + AbstractHashCodeDelegator.class.getSimpleName()); } @Test public void succeed_whenAFieldsHashCodeMethodCallsAnAbstractField_givenAConcretePrefabImplementationOfSaidField() { EqualsVerifier - .forClass(HashCodeInFieldDelegatesToAbstractMethod.class) - .withPrefabValues( - AbstractHashCodeDelegator.class, - new AbstractHashCodeDelegatorImpl(1), - new AbstractHashCodeDelegatorImpl(2) - ) - .verify(); + .forClass(HashCodeInFieldDelegatesToAbstractMethod.class) + .withPrefabValues( + AbstractHashCodeDelegator.class, + new AbstractHashCodeDelegatorImpl(1), + new AbstractHashCodeDelegatorImpl(2)) + .verify(); } @Test @@ -190,49 +166,42 @@ public void succeed_evenThoughToStringInSuperclassCallsAnAbstractMethod() { @Test public void succeed_evenThoughEqualsInSuperclassCallsAnAbstractMethod_givenUsingGetClass() { - EqualsVerifier - .forClass(AbstractEqualsUsingGetClassDelegatorImpl.class) - .usingGetClass() - .verify(); + EqualsVerifier.forClass(AbstractEqualsUsingGetClassDelegatorImpl.class).usingGetClass().verify(); } @Test public void originalMessageIsIncludedInErrorMessage_whenEqualsVerifierSignalsAnAbstractDelegationIssue() { ExpectedException - .when(() -> EqualsVerifier.forClass(ThrowsAbstractMethodErrorWithMessage.class).verify() - ) - .assertFailure() - .assertMessageContains("This is AbstractMethodError's original message"); + .when(() -> EqualsVerifier.forClass(ThrowsAbstractMethodErrorWithMessage.class).verify()) + .assertFailure() + .assertMessageContains("This is AbstractMethodError's original message"); } @Test public void failGracefully_whenAFieldsEqualsMethodDoesntDoAnIdentityCheckButCallsAnAbstractField() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(EqualsInFieldWithoutIdentityCheckDelegatesToAbstractMethod.class) - .verify() - ) - .assertFailure() - .assertCause(AbstractMethodError.class) - .assertMessageContains( - ABSTRACT_DELEGATION, - EQUALS_DELEGATES, - PREFAB, - AbstractEqualsWithoutIdentityCheckDelegator.class.getSimpleName() - ); + .when( + () -> EqualsVerifier + .forClass(EqualsInFieldWithoutIdentityCheckDelegatesToAbstractMethod.class) + .verify()) + .assertFailure() + .assertCause(AbstractMethodError.class) + .assertMessageContains( + ABSTRACT_DELEGATION, + EQUALS_DELEGATES, + PREFAB, + AbstractEqualsWithoutIdentityCheckDelegator.class.getSimpleName()); } @Test public void succeed_whenAFieldsEqualsMethodDoesntDoAnIdentityCheckButCallsAnAbstractField_givenAConcretePrefabImplementationOfSaidField() { EqualsVerifier - .forClass(EqualsInFieldWithoutIdentityCheckDelegatesToAbstractMethod.class) - .withPrefabValues( - AbstractEqualsWithoutIdentityCheckDelegator.class, - new AbstractEqualsWithoutIdentityCheckDelegatorImpl(1), - new AbstractEqualsWithoutIdentityCheckDelegatorImpl(2) - ) - .verify(); + .forClass(EqualsInFieldWithoutIdentityCheckDelegatesToAbstractMethod.class) + .withPrefabValues( + AbstractEqualsWithoutIdentityCheckDelegator.class, + new AbstractEqualsWithoutIdentityCheckDelegatorImpl(1), + new AbstractEqualsWithoutIdentityCheckDelegatorImpl(2)) + .verify(); } private abstract static class AbstractClass { @@ -339,8 +308,7 @@ public boolean equals(Object obj) { if (theAnswer()) { return true; } - AbstractEqualsWithoutIdentityCheckDelegator other = - (AbstractEqualsWithoutIdentityCheckDelegator) obj; + AbstractEqualsWithoutIdentityCheckDelegator other = (AbstractEqualsWithoutIdentityCheckDelegator) obj; return i == other.i; } @@ -351,7 +319,7 @@ public int hashCode() { } static final class AbstractEqualsWithoutIdentityCheckDelegatorImpl - extends AbstractEqualsWithoutIdentityCheckDelegator { + extends AbstractEqualsWithoutIdentityCheckDelegator { public AbstractEqualsWithoutIdentityCheckDelegatorImpl(int i) { super(i); @@ -473,8 +441,7 @@ public int hashCode() { } } - static final class AbstractEqualsUsingGetClassDelegatorImpl - extends AbstractEqualsUsingGetClassDelegator { + static final class AbstractEqualsUsingGetClassDelegatorImpl extends AbstractEqualsUsingGetClassDelegator { public AbstractEqualsUsingGetClassDelegatorImpl(int i) { super(i); @@ -535,8 +502,7 @@ public boolean equals(Object obj) { if (delegator != null) { delegator.abstractDelegation(); } - EqualsDelegatesToAbstractMethodInField other = - (EqualsDelegatesToAbstractMethodInField) obj; + EqualsDelegatesToAbstractMethodInField other = (EqualsDelegatesToAbstractMethodInField) obj; return i == other.i && Objects.equals(delegator, other.delegator); } @@ -612,8 +578,7 @@ public boolean equals(Object obj) { if (!(obj instanceof EqualsInFieldDelegatesToAbstractMethod)) { return false; } - EqualsInFieldDelegatesToAbstractMethod other = - (EqualsInFieldDelegatesToAbstractMethod) obj; + EqualsInFieldDelegatesToAbstractMethod other = (EqualsInFieldDelegatesToAbstractMethod) obj; return Objects.equals(delegator, other.delegator); } @@ -690,8 +655,7 @@ static class EqualsInFieldWithoutIdentityCheckDelegatesToAbstractMethod { private final AbstractEqualsWithoutIdentityCheckDelegator id; protected EqualsInFieldWithoutIdentityCheckDelegatesToAbstractMethod( - AbstractEqualsWithoutIdentityCheckDelegator id - ) { + AbstractEqualsWithoutIdentityCheckDelegator id) { this.id = id; } @@ -701,7 +665,7 @@ public final boolean equals(Object other) { return false; } EqualsInFieldWithoutIdentityCheckDelegatesToAbstractMethod that = - (EqualsInFieldWithoutIdentityCheckDelegatesToAbstractMethod) other; + (EqualsInFieldWithoutIdentityCheckDelegatesToAbstractMethod) other; return Objects.equals(id, that.id); } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/ArrayTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/ArrayTest.java index a689d4ec2..9386a7e22 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/ArrayTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/ArrayTest.java @@ -5,6 +5,7 @@ import java.util.Arrays; import java.util.Objects; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; @@ -13,29 +14,29 @@ public class ArrayTest { private static final String REGULAR_EQUALS = - "Array: == or regular equals() used instead of Arrays.equals() for field"; + "Array: == or regular equals() used instead of Arrays.equals() for field"; private static final String REGULAR_HASHCODE = - "Array: regular hashCode() used instead of Arrays.hashCode() for field"; + "Array: regular hashCode() used instead of Arrays.hashCode() for field"; private static final String MULTIDIMENSIONAL_EQUALS = - "Multidimensional array: ==, regular equals() or Arrays.equals() used instead of Arrays.deepEquals() for field"; + "Multidimensional array: ==, regular equals() or Arrays.equals() used instead of Arrays.deepEquals() for field"; private static final String MULTIDIMENSIONAL_HASHCODE = - "Multidimensional array: regular hashCode() or Arrays.hashCode() used instead of Arrays.deepHashCode() for field"; + "Multidimensional array: regular hashCode() or Arrays.hashCode() used instead of Arrays.deepHashCode() for field"; private static final String FIELD_NAME = "array"; @Test public void fail_whenRegularEqualsIsUsedInsteadOfArraysEquals_givenAPrimitiveArray() { ExpectedException - .when(() -> EqualsVerifier.forClass(PrimitiveArrayRegularEquals.class).verify()) - .assertFailure() - .assertMessageContains(REGULAR_EQUALS, FIELD_NAME); + .when(() -> EqualsVerifier.forClass(PrimitiveArrayRegularEquals.class).verify()) + .assertFailure() + .assertMessageContains(REGULAR_EQUALS, FIELD_NAME); } @Test public void fail_whenRegularHashCodeIsUsedInsteadOfArraysHashCode_givenAPrimitiveArray() { ExpectedException - .when(() -> EqualsVerifier.forClass(PrimitiveArrayRegularHashCode.class).verify()) - .assertFailure() - .assertMessageContains(REGULAR_HASHCODE, FIELD_NAME); + .when(() -> EqualsVerifier.forClass(PrimitiveArrayRegularHashCode.class).verify()) + .assertFailure() + .assertMessageContains(REGULAR_HASHCODE, FIELD_NAME); } @Test @@ -46,26 +47,25 @@ public void succeed_whenCorrectMethodsAreUsed_givenAPrimitiveArray() { @Test public void fail_whenArraysEqualsIsUsedInsteadOfDeepEquals_givenAMultidimensionalArray() { ExpectedException - .when(() -> EqualsVerifier.forClass(MultidimensionalArrayArraysEquals.class).verify()) - .assertFailure() - .assertMessageContains(MULTIDIMENSIONAL_EQUALS, FIELD_NAME); + .when(() -> EqualsVerifier.forClass(MultidimensionalArrayArraysEquals.class).verify()) + .assertFailure() + .assertMessageContains(MULTIDIMENSIONAL_EQUALS, FIELD_NAME); } @Test public void fail_whenRegularHashCodeIsUsedInsteadOfDeepHashCode_givenAMultidimensionalArray() { ExpectedException - .when(() -> EqualsVerifier.forClass(MultidimensionalArrayRegularHashCode.class).verify() - ) - .assertFailure() - .assertMessageContains(MULTIDIMENSIONAL_HASHCODE, FIELD_NAME); + .when(() -> EqualsVerifier.forClass(MultidimensionalArrayRegularHashCode.class).verify()) + .assertFailure() + .assertMessageContains(MULTIDIMENSIONAL_HASHCODE, FIELD_NAME); } @Test public void fail_whenArraysHashCodeIsUsedInsteadOfDeepHashCode_givenAMultidimensionalArray() { ExpectedException - .when(() -> EqualsVerifier.forClass(MultidimensionalArrayArraysHashCode.class).verify()) - .assertFailure() - .assertMessageContains(MULTIDIMENSIONAL_HASHCODE, FIELD_NAME); + .when(() -> EqualsVerifier.forClass(MultidimensionalArrayArraysHashCode.class).verify()) + .assertFailure() + .assertMessageContains(MULTIDIMENSIONAL_HASHCODE, FIELD_NAME); } @Test @@ -76,13 +76,9 @@ public void succeed_whenCorrectMethodsAreUsed_givenAMultidimensionalArray() { @Test public void failWithCorrectMessage_whenShallowHashCodeIsUsedOnSecondArray_givenTwoMultidimensionalArrays() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(TwoMultidimensionalArraysShallowHashCodeForSecond.class) - .verify() - ) - .assertFailure() - .assertMessageContains("second", MULTIDIMENSIONAL_HASHCODE); + .when(() -> EqualsVerifier.forClass(TwoMultidimensionalArraysShallowHashCodeForSecond.class).verify()) + .assertFailure() + .assertMessageContains("second", MULTIDIMENSIONAL_HASHCODE); } @Test @@ -93,27 +89,25 @@ public void succeed_whenCorrectMethodsAreUsed_givenAThreedimensionalArray() { @Test public void failWithRecursionError_whenClassContainsARecursionButAlsoAMutltiDimensionalArray() { ExpectedException - .when(() -> - EqualsVerifier.forClass(MultiDimensionalArrayAndRecursion.Board.class).verify() - ) - .assertThrows(AssertionError.class) - .assertMessageContains("Recursive datastructure"); + .when(() -> EqualsVerifier.forClass(MultiDimensionalArrayAndRecursion.Board.class).verify()) + .assertThrows(AssertionError.class) + .assertMessageContains("Recursive datastructure"); } @Test public void fail_whenRegularEqualsIsUsedInsteadOfArraysEquals_givenAnObjectArray() { ExpectedException - .when(() -> EqualsVerifier.forClass(ObjectArrayRegularEquals.class).verify()) - .assertFailure() - .assertMessageContains(REGULAR_EQUALS, FIELD_NAME); + .when(() -> EqualsVerifier.forClass(ObjectArrayRegularEquals.class).verify()) + .assertFailure() + .assertMessageContains(REGULAR_EQUALS, FIELD_NAME); } @Test public void fail_whenRegularHashCodeIsUsedInsteadOfArraysHashCode_givenAnObjectArray() { ExpectedException - .when(() -> EqualsVerifier.forClass(ObjectArrayRegularHashCode.class).verify()) - .assertFailure() - .assertMessageContains(REGULAR_HASHCODE, FIELD_NAME); + .when(() -> EqualsVerifier.forClass(ObjectArrayRegularHashCode.class).verify()) + .assertFailure() + .assertMessageContains(REGULAR_HASHCODE, FIELD_NAME); } @Test @@ -123,18 +117,15 @@ public void succeed_whenCorrectMethodsAreUsed_givenAnObjectArray() { @Test public void succeed_whenCorrectMethodsAreUsed_givenAnArrayAndAnUnusedField() { - EqualsVerifier - .forClass(ArrayAndSomethingUnused.class) - .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) - .verify(); + EqualsVerifier.forClass(ArrayAndSomethingUnused.class).suppress(Warning.ALL_FIELDS_SHOULD_BE_USED).verify(); } @Test public void succeed_whenArraysAreNotUsedInEquals_givenArrayFields() { EqualsVerifier - .forClass(ArraysAreUnused.class) - .suppress(Warning.INHERITED_DIRECTLY_FROM_OBJECT, Warning.ALL_FIELDS_SHOULD_BE_USED) - .verify(); + .forClass(ArraysAreUnused.class) + .suppress(Warning.INHERITED_DIRECTLY_FROM_OBJECT, Warning.ALL_FIELDS_SHOULD_BE_USED) + .verify(); } @Test @@ -154,10 +145,10 @@ public void succeed_whenArrayLengthIsInvariant() { int[][] x = { a, a, a }; int[][] y = { b, b, b }; EqualsVerifier - .forClass(Invariant.class) - .withPrefabValues(int[].class, a, b) - .withPrefabValues(int[][].class, x, y) - .verify(); + .forClass(Invariant.class) + .withPrefabValues(int[].class, a, b) + .withPrefabValues(int[][].class, x, y) + .verify(); } static final class PrimitiveArrayRegularEquals { @@ -179,7 +170,7 @@ public boolean equals(Object obj) { @Override public int hashCode() { - return (array == null) ? 0 : Arrays.hashCode(array); + return array == null ? 0 : Arrays.hashCode(array); } } @@ -225,7 +216,7 @@ public boolean equals(Object obj) { @Override public int hashCode() { - return (array == null) ? 0 : Arrays.hashCode(array); + return array == null ? 0 : Arrays.hashCode(array); } } @@ -248,7 +239,7 @@ public boolean equals(Object obj) { @Override public int hashCode() { - return (array == null) ? 0 : Arrays.deepHashCode(array); + return array == null ? 0 : Arrays.deepHashCode(array); } } @@ -271,7 +262,7 @@ public boolean equals(Object obj) { @Override public int hashCode() { - return (array == null) ? 0 : array.hashCode(); + return array == null ? 0 : array.hashCode(); } } @@ -317,7 +308,7 @@ public boolean equals(Object obj) { @Override public int hashCode() { - return (array == null) ? 0 : Arrays.deepHashCode(array); + return array == null ? 0 : Arrays.deepHashCode(array); } } @@ -326,10 +317,7 @@ static final class TwoMultidimensionalArraysShallowHashCodeForSecond { private final Object[][] first; private final Object[][] second; - public TwoMultidimensionalArraysShallowHashCodeForSecond( - Object[][] first, - Object[][] second - ) { + public TwoMultidimensionalArraysShallowHashCodeForSecond(Object[][] first, Object[][] second) { this.first = first; this.second = second; } @@ -340,7 +328,7 @@ public boolean equals(Object obj) { return false; } TwoMultidimensionalArraysShallowHashCodeForSecond other = - (TwoMultidimensionalArraysShallowHashCodeForSecond) obj; + (TwoMultidimensionalArraysShallowHashCodeForSecond) obj; return Arrays.deepEquals(first, other.first) && Arrays.deepEquals(second, other.second); } @@ -373,7 +361,7 @@ public boolean equals(Object obj) { @Override public int hashCode() { - return (array == null) ? 0 : Arrays.deepHashCode(array); + return array == null ? 0 : Arrays.deepHashCode(array); } } @@ -429,7 +417,7 @@ public boolean equals(Object obj) { @Override public int hashCode() { - return (array == null) ? 0 : Arrays.hashCode(array); + return array == null ? 0 : Arrays.hashCode(array); } } @@ -475,7 +463,7 @@ public boolean equals(Object obj) { @Override public int hashCode() { - return (array == null) ? 0 : Arrays.hashCode(array); + return array == null ? 0 : Arrays.hashCode(array); } } @@ -570,9 +558,7 @@ public boolean equals(Object obj) { return false; } Invariant other = (Invariant) obj; - return ( - Arrays.equals(array, other.array) && Arrays.deepEquals(multiArray, other.multiArray) - ); + return Arrays.equals(array, other.array) && Arrays.deepEquals(multiArray, other.multiArray); } @Override diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/BalancedAbstractnessTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/BalancedAbstractnessTest.java index 22106c418..b303e1f63 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/BalancedAbstractnessTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/BalancedAbstractnessTest.java @@ -23,45 +23,41 @@ public class BalancedAbstractnessTest { @Test public void fail_whenBothEqualsAndHashCodeAreAbstract() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(AbstractBoth.class) - .suppress(Warning.INHERITED_DIRECTLY_FROM_OBJECT) - .verify() - ) - .assertFailure() - .assertMessageContains(BOTH_ARE_ABSTRACT, AbstractBoth.class.getSimpleName()); + .when( + () -> EqualsVerifier + .forClass(AbstractBoth.class) + .suppress(Warning.INHERITED_DIRECTLY_FROM_OBJECT) + .verify()) + .assertFailure() + .assertMessageContains(BOTH_ARE_ABSTRACT, AbstractBoth.class.getSimpleName()); } @Test public void fail_whenEqualsIsAbstract() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(AbstractEquals.class) - .suppress(Warning.INHERITED_DIRECTLY_FROM_OBJECT) - .verify() - ) - .assertFailure() - .assertMessageContains( - EQUALS_IS_ABSTRACT, - HASHCODE_IS_NOT, - BOTH_SHOULD_BE_CONCRETE, - AbstractEquals.class.getSimpleName() - ); + .when( + () -> EqualsVerifier + .forClass(AbstractEquals.class) + .suppress(Warning.INHERITED_DIRECTLY_FROM_OBJECT) + .verify()) + .assertFailure() + .assertMessageContains( + EQUALS_IS_ABSTRACT, + HASHCODE_IS_NOT, + BOTH_SHOULD_BE_CONCRETE, + AbstractEquals.class.getSimpleName()); } @Test public void fail_whenHashCodeIsAbstract() { ExpectedException - .when(() -> EqualsVerifier.forClass(AbstractHashCode.class).verify()) - .assertFailure() - .assertMessageContains( - HASHCODE_IS_ABSTRACT, - EQUALS_IS_NOT, - BOTH_SHOULD_BE_CONCRETE, - AbstractHashCode.class.getSimpleName() - ); + .when(() -> EqualsVerifier.forClass(AbstractHashCode.class).verify()) + .assertFailure() + .assertMessageContains( + HASHCODE_IS_ABSTRACT, + EQUALS_IS_NOT, + BOTH_SHOULD_BE_CONCRETE, + AbstractHashCode.class.getSimpleName()); } @Test diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/BigDecimalTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/BigDecimalTest.java index ba96167ba..edefd1398 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/BigDecimalTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/BigDecimalTest.java @@ -4,6 +4,7 @@ import java.math.BigDecimal; import java.util.Objects; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.checkers.fieldchecks.BigDecimalFieldCheck; @@ -15,43 +16,34 @@ public class BigDecimalTest { @Test public void fail_whenBigDecimalsComparedUsingEqualsWithComparablyConsistentHashCode() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(BigDecimalEqualsWithComparablyConsistentHashCode.class) - .verify() - ) - .assertFailure() - .assertMessageContains( - BigDecimalFieldCheck.ERROR_DOC_TITLE, - "BigDecimal", - "equals", - "compareTo", - "bd", - Warning.BIGDECIMAL_EQUALITY.toString() - ); + .when(() -> EqualsVerifier.forClass(BigDecimalEqualsWithComparablyConsistentHashCode.class).verify()) + .assertFailure() + .assertMessageContains( + BigDecimalFieldCheck.ERROR_DOC_TITLE, + "BigDecimal", + "equals", + "compareTo", + "bd", + Warning.BIGDECIMAL_EQUALITY.toString()); } @Test public void fail_whenBigDecimalsComparedUsingCompareToWithInconsistentHashCode() { ExpectedException - .when(() -> EqualsVerifier.forClass(BigDecimalInconsistentHashCode.class).verify()) - .assertFailure() - .assertMessageContains( - BigDecimalFieldCheck.ERROR_DOC_TITLE, - "BigDecimal", - "hashCode", - "compareTo", - "bd", - Warning.BIGDECIMAL_EQUALITY.toString() - ); + .when(() -> EqualsVerifier.forClass(BigDecimalInconsistentHashCode.class).verify()) + .assertFailure() + .assertMessageContains( + BigDecimalFieldCheck.ERROR_DOC_TITLE, + "BigDecimal", + "hashCode", + "compareTo", + "bd", + Warning.BIGDECIMAL_EQUALITY.toString()); } @Test public void succeed_whenBigDecimalsComparedUsingEquals_givenBigDecimalEqualsWarningIsSuppressed() { - EqualsVerifier - .forClass(BigDecimalEquals.class) - .suppress(Warning.BIGDECIMAL_EQUALITY) - .verify(); + EqualsVerifier.forClass(BigDecimalEquals.class).suppress(Warning.BIGDECIMAL_EQUALITY).verify(); } @Test @@ -60,8 +52,7 @@ public void succeed_whenBigDecimalsComparedUsingCompareTo() { } /** - * Uses standard equals and hashCode for objects. - * 0 and 0.0 are not equal. + * Uses standard equals and hashCode for objects. 0 and 0.0 are not equal. */ private static final class BigDecimalEquals { @@ -87,8 +78,8 @@ public int hashCode() { } /** - * Uses compareTo for BigDecimal equality and ensures hashCode is equal for equal BigDecimal instances. - * 0 and 0.0 are equal and produce the same hashCode. + * Uses compareTo for BigDecimal equality and ensures hashCode is equal for equal BigDecimal instances. 0 and 0.0 + * are equal and produce the same hashCode. */ private static final class BigDecimalCompareTo { @@ -114,8 +105,8 @@ public int hashCode() { } /** - * Uses standard equals but with a consistent hashCode for comparably equal instances. - * 0 and 0.0 are not equal but produce the same hashCode. + * Uses standard equals but with a consistent hashCode for comparably equal instances. 0 and 0.0 are not equal but + * produce the same hashCode. */ private static final class BigDecimalEqualsWithComparablyConsistentHashCode { @@ -135,7 +126,7 @@ public boolean equals(Object obj) { return false; } BigDecimalEqualsWithComparablyConsistentHashCode other = - (BigDecimalEqualsWithComparablyConsistentHashCode) obj; + (BigDecimalEqualsWithComparablyConsistentHashCode) obj; return Objects.equals(bd, other.bd); } @@ -146,8 +137,8 @@ public int hashCode() { } /** - * Uses compareTo for BigDecimal equality but has hashCode that is inconsistent. - * 0 and 0.0 are equal but produce different hashCodes. + * Uses compareTo for BigDecimal equality but has hashCode that is inconsistent. 0 and 0.0 are equal but produce + * different hashCodes. */ private static final class BigDecimalInconsistentHashCode { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/DontOverrideEqualsTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/DontOverrideEqualsTest.java index 65200acfb..26081de7b 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/DontOverrideEqualsTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/DontOverrideEqualsTest.java @@ -11,17 +11,17 @@ public class DontOverrideEqualsTest { @Test public void fail_whenEqualsIsInheritedDirectlyFromObject() { ExpectedException - .when(() -> EqualsVerifier.forClass(NoEqualsNoHashCodeMethod.class).verify()) - .assertFailure() - .assertMessageContains("Equals is inherited directly from Object"); + .when(() -> EqualsVerifier.forClass(NoEqualsNoHashCodeMethod.class).verify()) + .assertFailure() + .assertMessageContains("Equals is inherited directly from Object"); } @Test public void succeed_whenEqualsIsInheritedDirectlyFromObject_givenDirectlyInheritedWarningIsSuppressed() { EqualsVerifier - .forClass(NoEqualsNoHashCodeMethod.class) - .suppress(Warning.INHERITED_DIRECTLY_FROM_OBJECT) - .verify(); + .forClass(NoEqualsNoHashCodeMethod.class) + .suppress(Warning.INHERITED_DIRECTLY_FROM_OBJECT) + .verify(); } @Test @@ -32,19 +32,19 @@ public void succeed_whenEqualsIsInheritedButNotFromObject() { @Test public void succeed_whenClassIsAPojoAndEqualsIsInheritedDirectlyFromObject_givenVariousWarningsAreSuppressed() { EqualsVerifier - .forClass(Pojo.class) - .suppress(Warning.INHERITED_DIRECTLY_FROM_OBJECT) - .suppress(Warning.NONFINAL_FIELDS, Warning.ALL_FIELDS_SHOULD_BE_USED) - .verify(); + .forClass(Pojo.class) + .suppress(Warning.INHERITED_DIRECTLY_FROM_OBJECT) + .suppress(Warning.NONFINAL_FIELDS, Warning.ALL_FIELDS_SHOULD_BE_USED) + .verify(); } @Test public void succeed_whenClassInheritsFromSomethingWithStateAndEqualsIsInheritedDirectlyFromObject_givenDetailMessageIsIgnored() { EqualsVerifier - .forClass(SubclassWithoutEqualsButWithStateFromSuper.class) - .suppress(Warning.INHERITED_DIRECTLY_FROM_OBJECT) - .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED, Warning.TRANSIENT_FIELDS) - .verify(); + .forClass(SubclassWithoutEqualsButWithStateFromSuper.class) + .suppress(Warning.INHERITED_DIRECTLY_FROM_OBJECT) + .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED, Warning.TRANSIENT_FIELDS) + .verify(); } static final class NoEqualsNoHashCodeMethod {} @@ -80,6 +80,5 @@ static class SomethingWithoutEqualsButWithState { private int i = 10; } - static final class SubclassWithoutEqualsButWithStateFromSuper - extends SomethingWithoutEqualsButWithState {} + static final class SubclassWithoutEqualsButWithStateFromSuper extends SomethingWithoutEqualsButWithState {} } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/EnumTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/EnumTest.java index 945f2be9b..e5d5d010f 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/EnumTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/EnumTest.java @@ -6,6 +6,7 @@ import java.util.Map; import java.util.Optional; import java.util.Set; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import org.junit.jupiter.api.Test; @@ -34,10 +35,7 @@ public void succeed_whenClassHasASingletonEnumAndUsesItInEquals() { @Test public void succeed_whenSingletonIsUsedWithoutNullCheck_givenNullFieldsWarningIsSuppressed() { - EqualsVerifier - .forClass(NullThrowingSingletonUser.class) - .suppress(Warning.NULL_FIELDS) - .verify(); + EqualsVerifier.forClass(NullThrowingSingletonUser.class).suppress(Warning.NULL_FIELDS).verify(); } @Test @@ -56,9 +54,7 @@ public void succeed_whenClassHasSingletonOptional() { } enum Enum { - ONE, - TWO, - THREE + ONE, TWO, THREE } enum Singleton { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/ExtendedReflexivityTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/ExtendedReflexivityTest.java index 4ad0cc3f3..89d70ac83 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/ExtendedReflexivityTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/ExtendedReflexivityTest.java @@ -4,6 +4,7 @@ import static nl.jqno.equalsverifier.internal.testhelpers.Util.defaultHashCode; import java.util.Objects; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; @@ -19,89 +20,78 @@ public void succeed_whenEqualsUsesEqualsMethodForObjects() { @Test public void fail_whenEqualsUsesDoubleEqualSignForObjects() { ExpectedException - .when(() -> EqualsVerifier.forClass(UsesDoubleEqualSign.class).verify()) - .assertFailure() - .assertMessageContains("Reflexivity", "== used instead of .equals()", "stringField"); + .when(() -> EqualsVerifier.forClass(UsesDoubleEqualSign.class).verify()) + .assertFailure() + .assertMessageContains("Reflexivity", "== used instead of .equals()", "stringField"); } @Test public void succeed_whenEqualsUsesDoubleEqualSignForObject_givenDoubleEqualWarningIsSuppressed() { - EqualsVerifier - .forClass(UsesDoubleEqualSign.class) - .suppress(Warning.REFERENCE_EQUALITY) - .verify(); + EqualsVerifier.forClass(UsesDoubleEqualSign.class).suppress(Warning.REFERENCE_EQUALITY).verify(); } @Test public void fail_whenEqualsUsesDoubleEqualSignForBoxedCharacterPrimitives() { ExpectedException - .when(() -> - EqualsVerifier.forClass(UsesDoubleEqualSignOnBoxedCharacterPrimitive.class).verify() - ) - .assertFailure() - .assertMessageContains("Reflexivity", "== used instead of .equals()", "characterField"); + .when(() -> EqualsVerifier.forClass(UsesDoubleEqualSignOnBoxedCharacterPrimitive.class).verify()) + .assertFailure() + .assertMessageContains("Reflexivity", "== used instead of .equals()", "characterField"); } @Test public void succeed_whenEqualsUsesDoubleEqualSignForBoxedCharacterPrimitives_givenDoubleEqualWarningIsSuppressed() { EqualsVerifier - .forClass(UsesDoubleEqualSignOnBoxedCharacterPrimitive.class) - .suppress(Warning.REFERENCE_EQUALITY) - .verify(); + .forClass(UsesDoubleEqualSignOnBoxedCharacterPrimitive.class) + .suppress(Warning.REFERENCE_EQUALITY) + .verify(); } @Test public void fail_whenEqualsUsesDoubleEqualSignForBoxedIntegerPrimitives() { ExpectedException - .when(() -> - EqualsVerifier.forClass(UsesDoubleEqualSignOnBoxedIntegerPrimitive.class).verify() - ) - .assertFailure() - .assertMessageContains("Reflexivity", "== used instead of .equals()", "integerField"); + .when(() -> EqualsVerifier.forClass(UsesDoubleEqualSignOnBoxedIntegerPrimitive.class).verify()) + .assertFailure() + .assertMessageContains("Reflexivity", "== used instead of .equals()", "integerField"); } @Test public void succeed_whenEqualsUsesDoubleEqualSignForBoxedIntegerPrimitives_givenDoubleEqualWarningIsSuppressed() { EqualsVerifier - .forClass(UsesDoubleEqualSignOnBoxedIntegerPrimitive.class) - .suppress(Warning.REFERENCE_EQUALITY) - .verify(); + .forClass(UsesDoubleEqualSignOnBoxedIntegerPrimitive.class) + .suppress(Warning.REFERENCE_EQUALITY) + .verify(); } @Test public void fail_whenEqualsUsesDoubleEqualSignForBoxedLongPrimitives() { ExpectedException - .when(() -> - EqualsVerifier.forClass(UsesDoubleEqualSignOnBoxedLongPrimitive.class).verify() - ) - .assertFailure() - .assertMessageContains("Reflexivity", "== used instead of .equals()", "longField"); + .when(() -> EqualsVerifier.forClass(UsesDoubleEqualSignOnBoxedLongPrimitive.class).verify()) + .assertFailure() + .assertMessageContains("Reflexivity", "== used instead of .equals()", "longField"); } @Test public void succeed_whenEqualsUsesDoubleEqualSignForBoxedLongPrimitives_givenDoubleEqualWarningIsSuppressed() { EqualsVerifier - .forClass(UsesDoubleEqualSignOnBoxedLongPrimitive.class) - .suppress(Warning.REFERENCE_EQUALITY) - .verify(); + .forClass(UsesDoubleEqualSignOnBoxedLongPrimitive.class) + .suppress(Warning.REFERENCE_EQUALITY) + .verify(); } @Test public void fail_whenEqualsUsesDoubleEqualSignForBoxedShortPrimitives() { ExpectedException - .when(() -> - EqualsVerifier.forClass(UsesDoubleEqualSignOnBoxedShortPrimitive.class).verify() - ) - .assertFailure() - .assertMessageContains("Reflexivity", "== used instead of .equals()", "shortField"); + .when(() -> EqualsVerifier.forClass(UsesDoubleEqualSignOnBoxedShortPrimitive.class).verify()) + .assertFailure() + .assertMessageContains("Reflexivity", "== used instead of .equals()", "shortField"); } @Test public void succeed_whenEqualsUsesDoubleEqualSignForBoxedShortPrimitives_givenDoubleEqualWarningIsSuppressed() { EqualsVerifier - .forClass(UsesDoubleEqualSignOnBoxedShortPrimitive.class) - .suppress(Warning.REFERENCE_EQUALITY) - .verify(); + .forClass(UsesDoubleEqualSignOnBoxedShortPrimitive.class) + .suppress(Warning.REFERENCE_EQUALITY) + .verify(); } @Test @@ -178,8 +168,7 @@ public boolean equals(Object obj) { if (!(obj instanceof UsesDoubleEqualSignOnBoxedCharacterPrimitive)) { return false; } - UsesDoubleEqualSignOnBoxedCharacterPrimitive other = - (UsesDoubleEqualSignOnBoxedCharacterPrimitive) obj; + UsesDoubleEqualSignOnBoxedCharacterPrimitive other = (UsesDoubleEqualSignOnBoxedCharacterPrimitive) obj; return characterField == other.characterField; } @@ -202,8 +191,7 @@ public boolean equals(Object obj) { if (!(obj instanceof UsesDoubleEqualSignOnBoxedIntegerPrimitive)) { return false; } - UsesDoubleEqualSignOnBoxedIntegerPrimitive other = - (UsesDoubleEqualSignOnBoxedIntegerPrimitive) obj; + UsesDoubleEqualSignOnBoxedIntegerPrimitive other = (UsesDoubleEqualSignOnBoxedIntegerPrimitive) obj; return integerField == other.integerField; } @@ -226,8 +214,7 @@ public boolean equals(Object obj) { if (!(obj instanceof UsesDoubleEqualSignOnBoxedLongPrimitive)) { return false; } - UsesDoubleEqualSignOnBoxedLongPrimitive other = - (UsesDoubleEqualSignOnBoxedLongPrimitive) obj; + UsesDoubleEqualSignOnBoxedLongPrimitive other = (UsesDoubleEqualSignOnBoxedLongPrimitive) obj; return longField == other.longField; } @@ -250,8 +237,7 @@ public boolean equals(Object obj) { if (!(obj instanceof UsesDoubleEqualSignOnBoxedShortPrimitive)) { return false; } - UsesDoubleEqualSignOnBoxedShortPrimitive other = - (UsesDoubleEqualSignOnBoxedShortPrimitive) obj; + UsesDoubleEqualSignOnBoxedShortPrimitive other = (UsesDoubleEqualSignOnBoxedShortPrimitive) obj; return shortField == other.shortField; } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/ExternalApiClassesTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/ExternalApiClassesTest.java index a4d25a0cb..8ba378da3 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/ExternalApiClassesTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/ExternalApiClassesTest.java @@ -3,12 +3,13 @@ import static nl.jqno.equalsverifier.internal.testhelpers.Util.defaultEquals; import static nl.jqno.equalsverifier.internal.testhelpers.Util.defaultHashCode; -import com.google.common.base.Optional; -import com.google.common.collect.*; -import com.google.common.reflect.TypeToken; import java.math.BigDecimal; import javax.naming.Reference; import javax.swing.tree.DefaultMutableTreeNode; + +import com.google.common.base.Optional; +import com.google.common.collect.*; +import com.google.common.reflect.TypeToken; import nl.jqno.equalsverifier.EqualsVerifier; import org.joda.time.*; import org.junit.jupiter.api.Test; @@ -98,16 +99,15 @@ static final class GuavaMultisetContainer { private final ImmutableSortedMultiset immutableSortedMultiset; public GuavaMultisetContainer( - Multiset multiset, - SortedMultiset sortedMultiset, - HashMultiset hashMultiset, - TreeMultiset treeMultiset, - LinkedHashMultiset linkedHashMultiset, - ConcurrentHashMultiset concurrentHashMultiset, - EnumMultiset enumMultiset, - ImmutableMultiset immutableMultiset, - ImmutableSortedMultiset immutableSortedMultiset - ) { + Multiset multiset, + SortedMultiset sortedMultiset, + HashMultiset hashMultiset, + TreeMultiset treeMultiset, + LinkedHashMultiset linkedHashMultiset, + ConcurrentHashMultiset concurrentHashMultiset, + EnumMultiset enumMultiset, + ImmutableMultiset immutableMultiset, + ImmutableSortedMultiset immutableSortedMultiset) { this.multiset = multiset; this.sortedMultiset = sortedMultiset; this.hashMultiset = hashMultiset; @@ -147,19 +147,18 @@ static final class GuavaMultimapContainer { private final ImmutableSetMultimap immutableSetMultimap; public GuavaMultimapContainer( - Multimap multimap, - ListMultimap listMultimap, - SetMultimap setMultimap, - SortedSetMultimap sortedSetMultimap, - ArrayListMultimap arrayListMultimap, - HashMultimap hashMultimap, - LinkedListMultimap linkedListMultimap, - LinkedHashMultimap linkedHashMultimap, - TreeMultimap treeMultimap, - ImmutableMultimap immutableMultimap, - ImmutableListMultimap immutableListMultimap, - ImmutableSetMultimap immutableSetMultimap - ) { + Multimap multimap, + ListMultimap listMultimap, + SetMultimap setMultimap, + SortedSetMultimap sortedSetMultimap, + ArrayListMultimap arrayListMultimap, + HashMultimap hashMultimap, + LinkedListMultimap linkedListMultimap, + LinkedHashMultimap linkedHashMultimap, + TreeMultimap treeMultimap, + ImmutableMultimap immutableMultimap, + ImmutableListMultimap immutableListMultimap, + ImmutableSetMultimap immutableSetMultimap) { this.multimap = multimap; this.listMultimap = listMultimap; this.setMultimap = setMultimap; @@ -195,12 +194,11 @@ static final class GuavaBiMapContainer { private final ImmutableBiMap immutableBiMap; public GuavaBiMapContainer( - BiMap biMap, - HashBiMap hashBiMap, - EnumBiMap enumBiMap, - EnumHashBiMap enumHashBiMap, - ImmutableBiMap immutableBiMap - ) { + BiMap biMap, + HashBiMap hashBiMap, + EnumBiMap enumBiMap, + EnumHashBiMap enumHashBiMap, + ImmutableBiMap immutableBiMap) { this.biMap = biMap; this.hashBiMap = hashBiMap; this.enumBiMap = enumBiMap; @@ -229,12 +227,11 @@ static final class GuavaTableContainer { private final ImmutableTable immutableTable; public GuavaTableContainer( - Table table, - HashBasedTable hashBasedTable, - TreeBasedTable treeBasedTable, - ArrayTable arrayTable, - ImmutableTable immutableTable - ) { + Table table, + HashBasedTable hashBasedTable, + TreeBasedTable treeBasedTable, + ArrayTable arrayTable, + ImmutableTable immutableTable) { this.table = table; this.hashBasedTable = hashBasedTable; this.treeBasedTable = treeBasedTable; @@ -263,12 +260,11 @@ static final class GuavaRegularCollectionsContainer { private final TreeRangeSet treeRangeSet; public GuavaRegularCollectionsContainer( - EvictingQueue evictingQueue, - MinMaxPriorityQueue minMaxPriorityQueue, - RangeSet rangeSet, - ImmutableRangeSet immutableRangeSet, - TreeRangeSet treeRangeSet - ) { + EvictingQueue evictingQueue, + MinMaxPriorityQueue minMaxPriorityQueue, + RangeSet rangeSet, + ImmutableRangeSet immutableRangeSet, + TreeRangeSet treeRangeSet) { this.evictingQueue = evictingQueue; this.minMaxPriorityQueue = minMaxPriorityQueue; this.rangeSet = rangeSet; @@ -298,13 +294,12 @@ static final class GuavaImmutableContainer { private final ImmutableSortedSet iSortedSet; public GuavaImmutableContainer( - ImmutableCollection immutableCollection, - ImmutableList immutableList, - ImmutableMap immutableMap, - ImmutableSet immutableSet, - ImmutableSortedMap iSortedMap, - ImmutableSortedSet iSortedSet - ) { + ImmutableCollection immutableCollection, + ImmutableList immutableList, + ImmutableMap immutableMap, + ImmutableSet immutableSet, + ImmutableSortedMap iSortedMap, + ImmutableSortedSet iSortedSet) { this.iCollection = immutableCollection; this.iList = immutableList; this.iMap = immutableMap; @@ -332,11 +327,7 @@ static final class GuavaOtherContainer { private final Optional optional; private final TypeToken typeToken; - public GuavaOtherContainer( - Range range, - Optional optional, - TypeToken typeToken - ) { + public GuavaOtherContainer(Range range, Optional optional, TypeToken typeToken) { this.range = range; this.optional = optional; this.typeToken = typeToken; @@ -368,17 +359,16 @@ static final class JodaTimeContainer { private final MonthDay monthDay; public JodaTimeContainer( - LocalDate localDate, - LocalTime localTime, - LocalDateTime localDateTime, - Chronology chronology, - DateTimeZone dateTimeZone, - Partial partial, - PeriodType periodType, - Period period, - YearMonth yearMonth, - MonthDay monthDay - ) { + LocalDate localDate, + LocalTime localTime, + LocalDateTime localDateTime, + Chronology chronology, + DateTimeZone dateTimeZone, + Partial partial, + PeriodType periodType, + Period period, + YearMonth yearMonth, + MonthDay monthDay) { this.localDate = localDate; this.localTime = localTime; this.localDateTime = localDateTime; diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/FloatAndDoubleTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/FloatAndDoubleTest.java index 9dfa4f5fe..ce4cb8c64 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/FloatAndDoubleTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/FloatAndDoubleTest.java @@ -14,17 +14,17 @@ public class FloatAndDoubleTest { @Test public void fail_whenFloatsAreComparedByReference() { ExpectedException - .when(() -> EqualsVerifier.forClass(ComparePrimitiveFloatsByReference.class).verify()) - .assertFailure() - .assertMessageContains(FLOAT, "f"); + .when(() -> EqualsVerifier.forClass(ComparePrimitiveFloatsByReference.class).verify()) + .assertFailure() + .assertMessageContains(FLOAT, "f"); } @Test public void fail_whenObjectFloatsAreComparedByReference() { ExpectedException - .when(() -> EqualsVerifier.forClass(CompareObjectFloatByReference.class).verify()) - .assertFailure() - .assertMessageContains(FLOAT, "f"); + .when(() -> EqualsVerifier.forClass(CompareObjectFloatByReference.class).verify()) + .assertFailure() + .assertMessageContains(FLOAT, "f"); } @Test @@ -35,17 +35,17 @@ public void succeed_whenFloatsAreComparedWithFloatCompare() { @Test public void fail_whenDoublesAreComparedByReference() { ExpectedException - .when(() -> EqualsVerifier.forClass(ComparePrimitiveDoubleByReference.class).verify()) - .assertFailure() - .assertMessageContains(DOUBLE, "d"); + .when(() -> EqualsVerifier.forClass(ComparePrimitiveDoubleByReference.class).verify()) + .assertFailure() + .assertMessageContains(DOUBLE, "d"); } @Test public void fail_whenObjectDoublesAreComparedByReference() { ExpectedException - .when(() -> EqualsVerifier.forClass(CompareObjectDoubleByReference.class).verify()) - .assertFailure() - .assertMessageContains(DOUBLE, "d"); + .when(() -> EqualsVerifier.forClass(CompareObjectDoubleByReference.class).verify()) + .assertFailure() + .assertMessageContains(DOUBLE, "d"); } @Test diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/GenericTypesTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/GenericTypesTest.java index c3cce62cf..fa57f2eda 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/GenericTypesTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/GenericTypesTest.java @@ -3,10 +3,11 @@ import static nl.jqno.equalsverifier.internal.testhelpers.Util.defaultEquals; import static nl.jqno.equalsverifier.internal.testhelpers.Util.defaultHashCode; -import com.google.common.collect.*; import java.util.*; import java.util.concurrent.atomic.AtomicReferenceArray; import java.util.function.Supplier; + +import com.google.common.collect.*; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; @@ -108,27 +109,25 @@ public void succeed_whenClassHasTypeVariableThatExtendsSomethingThatSupersSometh @Test public void failGracefully_whenClassHasASelfReferenceGenericParameter() { ExpectedException - .when(() -> EqualsVerifier.forClass(SelfReferringGenericType.class).verify()) - .assertFailure() - .assertMessageContains( - "Reflection error", - "try adding a prefab value", - "field wrapped", - "of type " + SelfReferringGenericType.class.getName() - ); + .when(() -> EqualsVerifier.forClass(SelfReferringGenericType.class).verify()) + .assertFailure() + .assertMessageContains( + "Reflection error", + "try adding a prefab value", + "field wrapped", + "of type " + SelfReferringGenericType.class.getName()); } @Test public void succeed_whenClassHasASelfReferenceGenericParameter_givenPrefabValues() { EqualsVerifier - .forClass(SelfReferringGenericType.class) - .withPrefabValues( - SelfReferringGenericType.class, - new SelfReferringGenericType<>(1), - new SelfReferringGenericType<>(2) - ) - .suppress(Warning.NONFINAL_FIELDS) - .verify(); + .forClass(SelfReferringGenericType.class) + .withPrefabValues( + SelfReferringGenericType.class, + new SelfReferringGenericType<>(1), + new SelfReferringGenericType<>(2)) + .suppress(Warning.NONFINAL_FIELDS) + .verify(); } @Test @@ -138,10 +137,7 @@ public void succeed_whenClassContainsAMapWithAnArray() { @Test public void succeed_whenClassContainsAClassThatContainsAMapWithArray() { - EqualsVerifier - .forClass(ArrayMapContainerContainer.class) - .withNonnullFields("mapContainer") - .verify(); + EqualsVerifier.forClass(ArrayMapContainerContainer.class).withNonnullFields("mapContainer").verify(); } static final class GenericContainerWithBuiltin { @@ -198,10 +194,9 @@ static final class JavaGenericTypeContainer { private final AtomicReferenceArray atomicReferenceArray; public JavaGenericTypeContainer( - Optional optional, - Supplier supplier, - AtomicReferenceArray atomicReferenceArray - ) { + Optional optional, + Supplier supplier, + AtomicReferenceArray atomicReferenceArray) { this.optional = optional; this.supplier = supplier; this.atomicReferenceArray = atomicReferenceArray; @@ -219,14 +214,10 @@ public boolean equals(Object obj) { Point thisSupplierPoint = supplier != null ? supplier.get() : null; Point thatSupplierPoint = other.supplier != null ? other.supplier.get() : null; Point thisAraPoint = atomicReferenceArray != null ? atomicReferenceArray.get(0) : null; - Point thatAraPoint = other.atomicReferenceArray != null - ? other.atomicReferenceArray.get(0) - : null; - return ( - Objects.equals(thisOptionalPoint, thatOptionalPoint) && - Objects.equals(thisSupplierPoint, thatSupplierPoint) && - Objects.equals(thisAraPoint, thatAraPoint) - ); + Point thatAraPoint = other.atomicReferenceArray != null ? other.atomicReferenceArray.get(0) : null; + return Objects.equals(thisOptionalPoint, thatOptionalPoint) + && Objects.equals(thisSupplierPoint, thatSupplierPoint) + && Objects.equals(thisAraPoint, thatAraPoint); } // CHECKSTYLE ON: NPathComplexity @@ -781,12 +772,8 @@ public boolean equals(Object obj) { if (!(obj instanceof TwoGenericsContainerWithIntrospection)) { return false; } - TwoGenericsContainerWithIntrospection other = - (TwoGenericsContainerWithIntrospection) obj; - return ( - Objects.equals(stringList, other.stringList) && - Objects.equals(intList, other.intList) - ); + TwoGenericsContainerWithIntrospection other = (TwoGenericsContainerWithIntrospection) obj; + return Objects.equals(stringList, other.stringList) && Objects.equals(intList, other.intList); } @Override diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/JavaApiClassesTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/JavaApiClassesTest.java index ace6f1670..0b7ad9275 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/JavaApiClassesTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/JavaApiClassesTest.java @@ -23,6 +23,7 @@ import java.util.concurrent.locks.StampedLock; import java.util.function.Supplier; import java.util.regex.Pattern; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.testhelpers.types.TypeHelper; @@ -75,10 +76,10 @@ public void succeed_whenClassContainsExceptions() { @Test public void succeed_whenClassContainsReflectionApiClass() { EqualsVerifier - .forClass(ReflectionClassesContainer.class) - // Because java.lang.reflect.Constructor's hashCode() is unhelpful - .suppress(Warning.STRICT_HASHCODE) - .verify(); + .forClass(ReflectionClassesContainer.class) + // Because java.lang.reflect.Constructor's hashCode() is unhelpful + .suppress(Warning.STRICT_HASHCODE) + .verify(); } @Test @@ -103,18 +104,15 @@ public void succeed_whenClassContainsAThreadLocalField() { @Test public void succeed_whenClassContainsStringBuilderThatCallsToStringInEquals() { - EqualsVerifier - .forClass(StringBuilderContainer.class) - .suppress(Warning.NULL_FIELDS) - .verify(); + EqualsVerifier.forClass(StringBuilderContainer.class).suppress(Warning.NULL_FIELDS).verify(); } @Test public void succeed_whenClassContainsClassesButDoesntUseThemInEquals() { EqualsVerifier - .forClass(UnusedInEqualsButPresentInClassContainer.class) - .suppress(Warning.INHERITED_DIRECTLY_FROM_OBJECT, Warning.ALL_FIELDS_SHOULD_BE_USED) - .verify(); + .forClass(UnusedInEqualsButPresentInClassContainer.class) + .suppress(Warning.INHERITED_DIRECTLY_FROM_OBJECT, Warning.ALL_FIELDS_SHOULD_BE_USED) + .verify(); } abstract static class CollectionContainer { @@ -180,13 +178,12 @@ static final class ListContainer extends CollectionContainer { private final Stack stack; public ListContainer( - List list, - CopyOnWriteArrayList copyOnWriteArrayList, - LinkedList linkedList, - ArrayList arrayList, - Vector vector, - Stack stack - ) { + List list, + CopyOnWriteArrayList copyOnWriteArrayList, + LinkedList linkedList, + ArrayList arrayList, + Vector vector, + Stack stack) { this.list = list; this.copyOnWriteArrayList = copyOnWriteArrayList; this.linkedList = linkedList; @@ -224,14 +221,13 @@ static final class SetContainer extends CollectionContainer { private final EnumSet enumSet; public SetContainer( - Set set, - SortedSet sortedSet, - NavigableSet navigableSet, - CopyOnWriteArraySet copyOnWriteArraySet, - HashSet hashSet, - TreeSet treeSet, - EnumSet enumSet - ) { + Set set, + SortedSet sortedSet, + NavigableSet navigableSet, + CopyOnWriteArraySet copyOnWriteArraySet, + HashSet hashSet, + TreeSet treeSet, + EnumSet enumSet) { this.set = set; this.sortedSet = sortedSet; this.navigableSet = navigableSet; @@ -273,17 +269,16 @@ static final class QueueContainer extends CollectionContainer { private final SynchronousQueue synchronousQueue; public QueueContainer( - Queue queue, - BlockingQueue blockingQueue, - Deque deque, - BlockingDeque blockingDeque, - ArrayBlockingQueue arrayBlockingQueue, - ConcurrentLinkedQueue concurrentLinkedQueue, - DelayQueue delayQueue, - LinkedBlockingQueue linkedBlockingQueue, - PriorityBlockingQueue priorityBlockingQueue, - SynchronousQueue synchronousQueue - ) { + Queue queue, + BlockingQueue blockingQueue, + Deque deque, + BlockingDeque blockingDeque, + ArrayBlockingQueue arrayBlockingQueue, + ConcurrentLinkedQueue concurrentLinkedQueue, + DelayQueue delayQueue, + LinkedBlockingQueue linkedBlockingQueue, + PriorityBlockingQueue priorityBlockingQueue, + SynchronousQueue synchronousQueue) { this.queue = queue; this.blockingQueue = blockingQueue; this.deque = deque; @@ -331,19 +326,18 @@ static final class MapContainer extends CollectionContainer { private final EnumMap enumMap; public MapContainer( - Map map, - SortedMap sortedMap, - NavigableMap navigableMap, - ConcurrentNavigableMap concurrentNavigableMap, - ConcurrentHashMap concurrentHashMap, - HashMap hashMap, - Hashtable hashtable, - LinkedHashMap linkedHashMap, - Properties properties, - TreeMap treeMap, - WeakHashMap weakHashMap, - EnumMap enumMap - ) { + Map map, + SortedMap sortedMap, + NavigableMap navigableMap, + ConcurrentNavigableMap concurrentNavigableMap, + ConcurrentHashMap concurrentHashMap, + HashMap hashMap, + Hashtable hashtable, + LinkedHashMap linkedHashMap, + Properties properties, + TreeMap treeMap, + WeakHashMap weakHashMap, + EnumMap enumMap) { this.map = map; this.sortedMap = sortedMap; this.navigableMap = navigableMap; @@ -391,15 +385,14 @@ static final class NioBufferContainer { private final ShortBuffer shortBuffer; public NioBufferContainer( - Buffer buffer, - ByteBuffer byteBuffer, - CharBuffer charBuffer, - DoubleBuffer doubleBuffer, - FloatBuffer floatBuffer, - IntBuffer intBuffer, - LongBuffer longBuffer, - ShortBuffer shortBuffer - ) { + Buffer buffer, + ByteBuffer byteBuffer, + CharBuffer charBuffer, + DoubleBuffer doubleBuffer, + FloatBuffer floatBuffer, + IntBuffer intBuffer, + LongBuffer longBuffer, + ShortBuffer shortBuffer) { this.buffer = buffer; this.byteBuffer = byteBuffer; this.charBuffer = charBuffer; @@ -453,34 +446,33 @@ static final class CommonClassesContainer { private final PrintStream printStream; public CommonClassesContainer( - String string, - Integer integer, - BitSet bitset, - Calendar calendar, - Date date, - File file, - GregorianCalendar gregorianCalendar, - Pattern pattern, - DecimalFormat decimalFormat, - NumberFormat numberFormat, - SimpleDateFormat simpleDateFormat, - URI uri, - URL url, - UUID uuid, - InetAddress inetAddress, - Inet4Address inet4Address, - Inet6Address inet6Address, - InetSocketAddress inetSocketAddress, - Thread thread, - java.sql.Date sqlDate, - java.sql.Time sqlTime, - java.sql.Timestamp sqlTimestamp, - Currency currency, - EventObject eventObject, - Charset charset, - Semaphore semaphore, - PrintStream printStream - ) { + String string, + Integer integer, + BitSet bitset, + Calendar calendar, + Date date, + File file, + GregorianCalendar gregorianCalendar, + Pattern pattern, + DecimalFormat decimalFormat, + NumberFormat numberFormat, + SimpleDateFormat simpleDateFormat, + URI uri, + URL url, + UUID uuid, + InetAddress inetAddress, + Inet4Address inet4Address, + Inet6Address inet6Address, + InetSocketAddress inetSocketAddress, + Thread thread, + java.sql.Date sqlDate, + java.sql.Time sqlTime, + java.sql.Timestamp sqlTimestamp, + Currency currency, + EventObject eventObject, + Charset charset, + Semaphore semaphore, + PrintStream printStream) { this.string = string; this.integer = integer; this.bitset = bitset; @@ -552,33 +544,32 @@ static final class Java8ApiClassesContainer { private final LongSummaryStatistics longSummaryStatistics; public Java8ApiClassesContainer( - Optional optional, - OptionalDouble optionalDouble, - OptionalInt optionalInt, - OptionalLong optionalLong, - LocalDate localDate, - LocalTime localTime, - LocalDateTime localDateTime, - ZoneId zoneId, - ZoneOffset zoneOffset, - ZonedDateTime zonedDateTime, - DateTimeFormatter dateTimeFormatter, - CompletableFuture completableFuture, - StampedLock stampedLock, - Supplier supplier, - Clock clock, - Duration duration, - Instant instant, - MonthDay monthDay, - OffsetDateTime offsetDateTime, - OffsetTime offsetTime, - Period period, - Year year, - YearMonth yearMonth, - DoubleSummaryStatistics doubleSummaryStatistics, - IntSummaryStatistics intSummaryStatistics, - LongSummaryStatistics longSummaryStatistics - ) { + Optional optional, + OptionalDouble optionalDouble, + OptionalInt optionalInt, + OptionalLong optionalLong, + LocalDate localDate, + LocalTime localTime, + LocalDateTime localDateTime, + ZoneId zoneId, + ZoneOffset zoneOffset, + ZonedDateTime zonedDateTime, + DateTimeFormatter dateTimeFormatter, + CompletableFuture completableFuture, + StampedLock stampedLock, + Supplier supplier, + Clock clock, + Duration duration, + Instant instant, + MonthDay monthDay, + OffsetDateTime offsetDateTime, + OffsetTime offsetTime, + Period period, + Year year, + YearMonth yearMonth, + DoubleSummaryStatistics doubleSummaryStatistics, + IntSummaryStatistics intSummaryStatistics, + LongSummaryStatistics longSummaryStatistics) { this.optional = optional; this.optionalDouble = optionalDouble; this.optionalInt = optionalInt; @@ -625,11 +616,7 @@ static final class ExceptionsContainer { private final Exception exception; private final RuntimeException runtimeException; - public ExceptionsContainer( - Throwable throwable, - Exception exception, - RuntimeException runtimeException - ) { + public ExceptionsContainer(Throwable throwable, Exception exception, RuntimeException runtimeException) { this.throwable = throwable; this.exception = exception; this.runtimeException = runtimeException; @@ -654,12 +641,7 @@ static final class ReflectionClassesContainer { private final Field field; private final Constructor constructor; - public ReflectionClassesContainer( - Class type, - Method method, - Field field, - Constructor constructor - ) { + public ReflectionClassesContainer(Class type, Method method, Field field, Constructor constructor) { this.type = type; this.method = method; this.field = field; @@ -695,20 +677,19 @@ static final class AtomicClassesContainer { private final LongAccumulator longAccumulator; public AtomicClassesContainer( - AtomicBoolean atomicBoolean, - AtomicInteger atomicInteger, - AtomicIntegerArray atomicIntegerArray, - AtomicLong atomicLong, - AtomicLongArray atomicLongArray, - AtomicMarkableReference atomicMarkableReference, - AtomicReference atomicReference, - AtomicReferenceArray atomicReferenceArray, - AtomicStampedReference atomicStampedReference, - DoubleAdder doubleAdder, - DoubleAccumulator doubleAccumulator, - LongAdder longAdder, - LongAccumulator longAccumulator - ) { + AtomicBoolean atomicBoolean, + AtomicInteger atomicInteger, + AtomicIntegerArray atomicIntegerArray, + AtomicLong atomicLong, + AtomicLongArray atomicLongArray, + AtomicMarkableReference atomicMarkableReference, + AtomicReference atomicReference, + AtomicReferenceArray atomicReferenceArray, + AtomicStampedReference atomicStampedReference, + DoubleAdder doubleAdder, + DoubleAccumulator doubleAccumulator, + LongAdder longAdder, + LongAccumulator longAccumulator) { this.atomicBoolean = atomicBoolean; this.atomicInteger = atomicInteger; this.atomicIntegerArray = atomicIntegerArray; @@ -747,14 +728,13 @@ static final class AncientJavaApiClassesContainer { private final java.rmi.server.UID uid; public AncientJavaApiClassesContainer( - java.awt.color.ColorSpace awtColorSpace, - java.awt.color.ICC_ColorSpace iccColorSpace, - java.awt.color.ICC_Profile iccProfile, - java.awt.Font font, - java.awt.Image image, - java.rmi.dgc.VMID vmid, - java.rmi.server.UID uid - ) { + java.awt.color.ColorSpace awtColorSpace, + java.awt.color.ICC_ColorSpace iccColorSpace, + java.awt.color.ICC_Profile iccProfile, + java.awt.Font font, + java.awt.Image image, + java.rmi.dgc.VMID vmid, + java.rmi.server.UID uid) { this.awtColorSpace = awtColorSpace; this.iccColorSpace = iccColorSpace; this.iccProfile = iccProfile; diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/JavaCollectionSubclassTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/JavaCollectionSubclassTest.java index 9a1f438f8..3c5371c33 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/JavaCollectionSubclassTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/JavaCollectionSubclassTest.java @@ -1,6 +1,7 @@ package nl.jqno.equalsverifier.integration.extended_contract; import java.util.ArrayList; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; import org.junit.jupiter.api.Test; @@ -12,9 +13,9 @@ public class JavaCollectionSubclassTest { @Test public void failWithHelpfulMessage_whenVerifyingArrayListSubclass() { ExpectedException - .when(() -> EqualsVerifier.forClass(CustomArrayList.class).verify()) - .assertFailure() - .assertMessageContains(MESSAGE_FRAGMENT, ArrayList.class.getCanonicalName()); + .when(() -> EqualsVerifier.forClass(CustomArrayList.class).verify()) + .assertFailure() + .assertMessageContains(MESSAGE_FRAGMENT, ArrayList.class.getCanonicalName()); } private static final class CustomArrayList extends ArrayList { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/MapEntrySubclassTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/MapEntrySubclassTest.java index 9910bbc7c..a33fc2a99 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/MapEntrySubclassTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/MapEntrySubclassTest.java @@ -2,6 +2,7 @@ import java.util.Map; import java.util.Objects; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; import org.junit.jupiter.api.Test; @@ -11,9 +12,9 @@ class MapEntrySubclassTest { @Test void fails_whenMapEntryHashCodeContractIsNotHonored() { ExpectedException - .when(() -> EqualsVerifier.forClass(HashCodeContractNotHonored.class).verify()) - .assertFailure() - .assertMessageContains("Map.Entry: hashCode for", "should be", "but was"); + .when(() -> EqualsVerifier.forClass(HashCodeContractNotHonored.class).verify()) + .assertFailure() + .assertMessageContains("Map.Entry: hashCode for", "should be", "but was"); } @Test diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/ModulesTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/ModulesTest.java index b58a876a6..c8d2373b4 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/ModulesTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/ModulesTest.java @@ -2,6 +2,7 @@ import java.text.AttributedString; import java.util.Objects; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; @@ -10,9 +11,8 @@ import org.junit.jupiter.api.condition.JRE; /* - * Let's hope nobody needs prefab values for `java.text.AttributedString`, - * because we need a class here from je Java APIs that doesn't already - * have prefab values. + * Let's hope nobody needs prefab values for `java.text.AttributedString`, because we need a class here from je Java + * APIs that doesn't already have prefab values. */ public class ModulesTest { @@ -20,23 +20,22 @@ public class ModulesTest { @DisabledForJreRange(max = JRE.JAVA_11) public void giveProperErrorMessage_whenClassUnderTestIsInaccessible() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(AttributedString.class) - .suppress(Warning.INHERITED_DIRECTLY_FROM_OBJECT) - .verify() - ) - .assertFailure() - .assertMessageContains("The class", "Consider opening"); + .when( + () -> EqualsVerifier + .forClass(AttributedString.class) + .suppress(Warning.INHERITED_DIRECTLY_FROM_OBJECT) + .verify()) + .assertFailure() + .assertMessageContains("The class", "Consider opening"); } @Test @DisabledForJreRange(max = JRE.JAVA_11) public void giveProperErrorMessage_whenFieldIsInaccessible() { ExpectedException - .when(() -> EqualsVerifier.forClass(InaccessibleContainer.class).verify()) - .assertFailure() - .assertMessageContains("Field x", "Consider opening", "add prefab values"); + .when(() -> EqualsVerifier.forClass(InaccessibleContainer.class).verify()) + .assertFailure() + .assertMessageContains("Field x", "Consider opening", "add prefab values"); } static final class InaccessibleContainer { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/MutableStateTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/MutableStateTest.java index c228eea77..cb362291f 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/MutableStateTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/MutableStateTest.java @@ -4,6 +4,7 @@ import static nl.jqno.equalsverifier.internal.testhelpers.Util.defaultHashCode; import java.util.Arrays; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; @@ -17,49 +18,40 @@ public class MutableStateTest { @Test public void fail_whenClassHasAMutablePrimitiveField() { ExpectedException - .when(() -> EqualsVerifier.forClass(PrimitiveMutableField.class).verify()) - .assertFailure() - .assertMessageContains(MUTABILITY, "second"); + .when(() -> EqualsVerifier.forClass(PrimitiveMutableField.class).verify()) + .assertFailure() + .assertMessageContains(MUTABILITY, "second"); } @Test public void succeed_whenClassHasAMutablePrimitiveField_givenItDoesNotUseThatFieldInEquals() { - EqualsVerifier - .forClass(UnusedPrimitiveMutableField.class) - .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) - .verify(); + EqualsVerifier.forClass(UnusedPrimitiveMutableField.class).suppress(Warning.ALL_FIELDS_SHOULD_BE_USED).verify(); } @Test public void succeed_whenClassHasAMutablePrimitiveField_givenWarningIsSuppressed() { - EqualsVerifier - .forClass(PrimitiveMutableField.class) - .suppress(Warning.NONFINAL_FIELDS) - .verify(); + EqualsVerifier.forClass(PrimitiveMutableField.class).suppress(Warning.NONFINAL_FIELDS).verify(); } @Test public void fail_whenClassHasAMutableObjectField() { ExpectedException - .when(() -> EqualsVerifier.forClass(ObjectMutableField.class).verify()) - .assertFailure() - .assertMessageContains(MUTABILITY, FIELD_NAME); + .when(() -> EqualsVerifier.forClass(ObjectMutableField.class).verify()) + .assertFailure() + .assertMessageContains(MUTABILITY, FIELD_NAME); } @Test public void succeed_whenClassHasAMutableObjectField_givenWarningIsSuppressed() { - EqualsVerifier - .forClass(ObjectMutableField.class) - .suppress(Warning.NONFINAL_FIELDS) - .verify(); + EqualsVerifier.forClass(ObjectMutableField.class).suppress(Warning.NONFINAL_FIELDS).verify(); } @Test public void fail_whenClassHasAMutableEnumField() { ExpectedException - .when(() -> EqualsVerifier.forClass(EnumMutableField.class).verify()) - .assertFailure() - .assertMessageContains(MUTABILITY, FIELD_NAME); + .when(() -> EqualsVerifier.forClass(EnumMutableField.class).verify()) + .assertFailure() + .assertMessageContains(MUTABILITY, FIELD_NAME); } @Test @@ -70,9 +62,9 @@ public void succeed_whenClassHasAMutableEnumField_givenWarningIsSuppressed() { @Test public void fail_whenClassHasAMutableArrayField() { ExpectedException - .when(() -> EqualsVerifier.forClass(ArrayMutableField.class).verify()) - .assertFailure() - .assertMessageContains(MUTABILITY, FIELD_NAME); + .when(() -> EqualsVerifier.forClass(ArrayMutableField.class).verify()) + .assertFailure() + .assertMessageContains(MUTABILITY, FIELD_NAME); } @Test @@ -151,8 +143,7 @@ public int hashCode() { static final class EnumMutableField { public enum Enum { - RED, - BLUE + RED, BLUE } private Enum field; @@ -190,7 +181,7 @@ public boolean equals(Object obj) { @Override public int hashCode() { - return (field == null) ? 0 : Arrays.hashCode(field); + return field == null ? 0 : Arrays.hashCode(field); } } } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/NullFieldsTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/NullFieldsTest.java index 427b9c90b..2a4b7ffbc 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/NullFieldsTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/NullFieldsTest.java @@ -21,37 +21,37 @@ public class NullFieldsTest { @Test public void fail_whenEqualsThrowsNpeOnThissField() { ExpectedException - .when(() -> EqualsVerifier.forClass(EqualsThrowsNpeOnThis.class).verify()) - .assertFailure() - .assertCause(NullPointerException.class) - .assertMessageContains(NON_NULLITY, EQUALS, ON_THIS_FIELD, "color"); + .when(() -> EqualsVerifier.forClass(EqualsThrowsNpeOnThis.class).verify()) + .assertFailure() + .assertCause(NullPointerException.class) + .assertMessageContains(NON_NULLITY, EQUALS, ON_THIS_FIELD, "color"); } @Test public void fail_whenEqualsThrowsNpeOnOthersField() { ExpectedException - .when(() -> EqualsVerifier.forClass(EqualsThrowsNpeOnOther.class).verify()) - .assertFailure() - .assertCause(NullPointerException.class) - .assertMessageContains(NON_NULLITY, EQUALS, ON_THE_OTHER_FIELD, "color"); + .when(() -> EqualsVerifier.forClass(EqualsThrowsNpeOnOther.class).verify()) + .assertFailure() + .assertCause(NullPointerException.class) + .assertMessageContains(NON_NULLITY, EQUALS, ON_THE_OTHER_FIELD, "color"); } @Test public void fail_whenEqualsThrowsNpeOnStaticField() { ExpectedException - .when(() -> EqualsVerifier.forClass(EqualsThrowsNpeOnStatic.class).verify()) - .assertFailure() - .assertCause(NullPointerException.class) - .assertMessageContains(NON_NULLITY, EQUALS, ON_THE_OTHER_FIELD, "color"); + .when(() -> EqualsVerifier.forClass(EqualsThrowsNpeOnStatic.class).verify()) + .assertFailure() + .assertCause(NullPointerException.class) + .assertMessageContains(NON_NULLITY, EQUALS, ON_THE_OTHER_FIELD, "color"); } @Test public void fail_whenHashCodeThrowsNpe() { ExpectedException - .when(() -> EqualsVerifier.forClass(HashCodeThrowsNpe.class).verify()) - .assertFailure() - .assertCause(NullPointerException.class) - .assertMessageContains(NON_NULLITY, HASHCODE, "color"); + .when(() -> EqualsVerifier.forClass(HashCodeThrowsNpe.class).verify()) + .assertFailure() + .assertCause(NullPointerException.class) + .assertMessageContains(NON_NULLITY, HASHCODE, "color"); } @Test @@ -82,10 +82,10 @@ public void succeed_whenConstantFieldIsNull() { @Test public void fail_whenClassHasNullChecksForOnlySomeFields() { ExpectedException - .when(() -> EqualsVerifier.forClass(MixedNullFields.class).verify()) - .assertFailure() - .assertCause(NullPointerException.class) - .assertMessageContains(NON_NULLITY, EQUALS, ON_THIS_FIELD, "o"); + .when(() -> EqualsVerifier.forClass(MixedNullFields.class).verify()) + .assertFailure() + .assertCause(NullPointerException.class) + .assertMessageContains(NON_NULLITY, EQUALS, ON_THIS_FIELD, "o"); } @Test @@ -101,48 +101,39 @@ public void succeed_whenClassHasNullChecksForOnlySomeFields_givenTheOtherFieldIs @Test public void anExceptionIsThrown_whenANonExistingFieldIsGivenToWithNonnullFields() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(MixedNullFields.class) - .withNonnullFields("thisFieldDoesNotExist") - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "Precondition", - "class MixedNullFields does not contain field thisFieldDoesNotExist." - ); + .when(() -> EqualsVerifier.forClass(MixedNullFields.class).withNonnullFields("thisFieldDoesNotExist")) + .assertThrows(IllegalStateException.class) + .assertMessageContains( + "Precondition", + "class MixedNullFields does not contain field thisFieldDoesNotExist."); } @Test public void anExceptionIsThrown_whenWithNonnullFieldsOverlapsWithSuppressWarnings() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(MixedNullFields.class) - .withNonnullFields("o") - .suppress(Warning.NULL_FIELDS) - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "Precondition", - "you can call either withNonnullFields or suppress Warning.NULL_FIELDS, but not both." - ); + .when( + () -> EqualsVerifier + .forClass(MixedNullFields.class) + .withNonnullFields("o") + .suppress(Warning.NULL_FIELDS)) + .assertThrows(IllegalStateException.class) + .assertMessageContains( + "Precondition", + "you can call either withNonnullFields or suppress Warning.NULL_FIELDS, but not both."); } @Test public void anExceptionIsThrown_whenSuppressWarningsOverlapsWithWithNonnullFields() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(MixedNullFields.class) - .suppress(Warning.NULL_FIELDS) - .withNonnullFields("o") - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "Precondition", - "you can call either withNonnullFields or suppress Warning.NULL_FIELDS, but not both." - ); + .when( + () -> EqualsVerifier + .forClass(MixedNullFields.class) + .suppress(Warning.NULL_FIELDS) + .withNonnullFields("o")) + .assertThrows(IllegalStateException.class) + .assertMessageContains( + "Precondition", + "you can call either withNonnullFields or suppress Warning.NULL_FIELDS, but not both."); } static final class EqualsThrowsNpeOnThis { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/NullFieldsWithExceptionsTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/NullFieldsWithExceptionsTest.java index 58669030a..d7010a750 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/NullFieldsWithExceptionsTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/NullFieldsWithExceptionsTest.java @@ -4,6 +4,7 @@ import static nl.jqno.equalsverifier.internal.testhelpers.Util.defaultHashCode; import java.util.Objects; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; import org.junit.jupiter.api.Test; @@ -20,37 +21,37 @@ public class NullFieldsWithExceptionsTest { @Test public void recogniseUnderlyingNpe_whenIllegalArgumentExceptionIsThrownInEquals_givenFieldIsNull() { ExpectedException - .when(() -> EqualsVerifier.forClass(EqualsIllegalArgumentThrower.class).verify()) - .assertFailure() - .assertCause(IllegalArgumentException.class) - .assertMessageContains(EQUALS, THROWS, ILLEGAL_ARGUMENT_EXCEPTION, WHEN_FOO_IS_NULL); + .when(() -> EqualsVerifier.forClass(EqualsIllegalArgumentThrower.class).verify()) + .assertFailure() + .assertCause(IllegalArgumentException.class) + .assertMessageContains(EQUALS, THROWS, ILLEGAL_ARGUMENT_EXCEPTION, WHEN_FOO_IS_NULL); } @Test public void recogniseUnderlyingNpe_whenIllegalStateExceptionIsThrownInEquals_givenFieldIsNull() { ExpectedException - .when(() -> EqualsVerifier.forClass(EqualsIllegalStateThrower.class).verify()) - .assertFailure() - .assertCause(IllegalStateException.class) - .assertMessageContains(EQUALS, THROWS, ILLEGAL_STATE_EXCEPTION, WHEN_FOO_IS_NULL); + .when(() -> EqualsVerifier.forClass(EqualsIllegalStateThrower.class).verify()) + .assertFailure() + .assertCause(IllegalStateException.class) + .assertMessageContains(EQUALS, THROWS, ILLEGAL_STATE_EXCEPTION, WHEN_FOO_IS_NULL); } @Test public void recogniseUnderlyingNpe_whenIllegalArgumentExceptionIsThrownInHashCode_givenFieldIsNull() { ExpectedException - .when(() -> EqualsVerifier.forClass(HashCodeIllegalArgumentThrower.class).verify()) - .assertFailure() - .assertCause(IllegalArgumentException.class) - .assertMessageContains(HASH_CODE, THROWS, ILLEGAL_ARGUMENT_EXCEPTION, WHEN_FOO_IS_NULL); + .when(() -> EqualsVerifier.forClass(HashCodeIllegalArgumentThrower.class).verify()) + .assertFailure() + .assertCause(IllegalArgumentException.class) + .assertMessageContains(HASH_CODE, THROWS, ILLEGAL_ARGUMENT_EXCEPTION, WHEN_FOO_IS_NULL); } @Test public void recogniseUnderlyingNpe_whenIllegalStateExceptionIsThrownInHashCode_givenFieldIsNull() { ExpectedException - .when(() -> EqualsVerifier.forClass(HashCodeIllegalStateThrower.class).verify()) - .assertFailure() - .assertCause(IllegalStateException.class) - .assertMessageContains(HASH_CODE, THROWS, ILLEGAL_STATE_EXCEPTION, WHEN_FOO_IS_NULL); + .when(() -> EqualsVerifier.forClass(HashCodeIllegalStateThrower.class).verify()) + .assertFailure() + .assertCause(IllegalStateException.class) + .assertMessageContains(HASH_CODE, THROWS, ILLEGAL_STATE_EXCEPTION, WHEN_FOO_IS_NULL); } abstract static class EqualsThrower { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/SignatureTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/SignatureTest.java index 1668b83b3..3c3cb5f55 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/SignatureTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/SignatureTest.java @@ -3,6 +3,7 @@ import static nl.jqno.equalsverifier.internal.testhelpers.Util.defaultHashCode; import java.util.Objects; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; @@ -18,52 +19,44 @@ public class SignatureTest { public void fail_whenEqualsIsOverloadedWithTypeInsteadOfObject() { expectOverloadFailure( "Parameter should be an Object, not " + OverloadedWithOwnType.class.getSimpleName(), - () -> EqualsVerifier.forClass(OverloadedWithOwnType.class).verify() - ); + () -> EqualsVerifier.forClass(OverloadedWithOwnType.class).verify()); } @Test public void fail_whenEqualsIsOverloadedWithTwoParameters() { expectOverloadFailure( "Too many parameters", - () -> EqualsVerifier.forClass(OverloadedWithTwoParameters.class).verify() - ); + () -> EqualsVerifier.forClass(OverloadedWithTwoParameters.class).verify()); } @Test public void fail_whenEqualsIsOverloadedWithNoParameter() { - expectOverloadFailure( - "No parameter", - () -> EqualsVerifier.forClass(OverloadedWithNoParameter.class).verify() - ); + expectOverloadFailure("No parameter", () -> EqualsVerifier.forClass(OverloadedWithNoParameter.class).verify()); } @Test public void fail_whenEqualsIsOverloadedWithUnrelatedParameter() { expectOverloadFailure( "Parameter should be an Object", - () -> EqualsVerifier.forClass(OverloadedWithUnrelatedParameter.class).verify() - ); + () -> EqualsVerifier.forClass(OverloadedWithUnrelatedParameter.class).verify()); } @Test public void fail_whenEqualsIsProperlyOverriddenButAlsoOverloaded() { expectOverloadFailure( "More than one equals method found", - () -> - EqualsVerifier + () -> EqualsVerifier .forClass(OverloadedAndOverridden.class) .suppress(Warning.INHERITED_DIRECTLY_FROM_OBJECT) - .verify() - ); + .verify()); } @Test public void succeed_whenEqualsIsNeitherOverriddenOrOverloaded_givenInheritedDirectlyWarningIsSuppressed() { EqualsVerifier - .forClass(NoEqualsMethod.class) - .suppress(Warning.INHERITED_DIRECTLY_FROM_OBJECT, Warning.ALL_FIELDS_SHOULD_BE_USED) - .verify(); + .forClass(NoEqualsMethod.class) + .suppress(Warning.INHERITED_DIRECTLY_FROM_OBJECT, Warning.ALL_FIELDS_SHOULD_BE_USED) + .verify(); } @Test @@ -73,9 +66,9 @@ public void succeed_whenAStaticEqualsExists() { private void expectOverloadFailure(String extraMessage, Runnable runnable) { ExpectedException - .when(runnable) - .assertFailure() - .assertMessageContains(OVERLOADED, SIGNATURE_SHOULD_BE, SIGNATURE, extraMessage); + .when(runnable) + .assertFailure() + .assertMessageContains(OVERLOADED, SIGNATURE_SHOULD_BE, SIGNATURE, extraMessage); } static final class OverloadedWithOwnType { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/SignificantFieldsTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/SignificantFieldsTest.java index 00c51193c..6e336be2a 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/SignificantFieldsTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/SignificantFieldsTest.java @@ -4,6 +4,7 @@ import static nl.jqno.equalsverifier.internal.testhelpers.Util.defaultHashCode; import java.util.Objects; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; @@ -17,34 +18,22 @@ public class SignificantFieldsTest { @Test public void fail_whenEqualsUsesAFieldAndHashCodeDoesnt() { ExpectedException - .when(() -> EqualsVerifier.forClass(ExtraFieldInEquals.class).verify()) - .assertFailure() - .assertMessageContains( - "Significant fields", - "equals relies on", - "yNotUsed", - "but hashCode does not" - ); + .when(() -> EqualsVerifier.forClass(ExtraFieldInEquals.class).verify()) + .assertFailure() + .assertMessageContains("Significant fields", "equals relies on", "yNotUsed", "but hashCode does not"); } @Test public void succeed_whenEqualsUsesAFieldAndHashCodeDoesnt_givenStrictHashCodeWarningIsSuppressed() { - EqualsVerifier - .forClass(ExtraFieldInEquals.class) - .suppress(Warning.STRICT_HASHCODE) - .verify(); + EqualsVerifier.forClass(ExtraFieldInEquals.class).suppress(Warning.STRICT_HASHCODE).verify(); } @Test public void fail_whenHashCodeIsConstant() { ExpectedException - .when(() -> EqualsVerifier.forClass(ConstantHashCode.class).verify()) - .assertFailure() - .assertMessageContains( - "Significant fields", - "equals relies on", - "but hashCode does not" - ); + .when(() -> EqualsVerifier.forClass(ConstantHashCode.class).verify()) + .assertFailure() + .assertMessageContains("Significant fields", "equals relies on", "but hashCode does not"); } @Test @@ -55,31 +44,20 @@ public void succeed_whenHashCodeIsConstant_givenStrictHashCodeWarningIsSuppresse @Test public void fail_whenHashCodeUsesAFieldAndEqualsDoesnt() { ExpectedException - .when(() -> EqualsVerifier.forClass(ExtraFieldInHashCode.class).verify()) - .assertMessageContains( - "Significant fields", - "hashCode relies on", - "yNotUsed", - "but equals does not" - ); + .when(() -> EqualsVerifier.forClass(ExtraFieldInHashCode.class).verify()) + .assertMessageContains("Significant fields", "hashCode relies on", "yNotUsed", "but equals does not"); } @Test public void fail_whenHashCodeUsesAFieldAndEqualsDoesnt_givenStrictHashCodeWarningIsSuppressed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(ExtraFieldInHashCode.class) - .suppress(Warning.STRICT_HASHCODE) - .verify() - ) - .assertFailure() - .assertMessageContains( - "Significant fields", - "hashCode relies on", - "yNotUsed", - "but equals does not" - ); + .when( + () -> EqualsVerifier + .forClass(ExtraFieldInHashCode.class) + .suppress(Warning.STRICT_HASHCODE) + .verify()) + .assertFailure() + .assertMessageContains("Significant fields", "hashCode relies on", "yNotUsed", "but equals does not"); } @Test @@ -89,47 +67,43 @@ public void succeed_whenAllFieldsAreUsed_givenAllFieldsShouldBeUsed() { @Test public void succeed_whenAFieldIsUnused_givenAllFieldsWarningIsSuppressed() { - EqualsVerifier - .forClass(OneFieldUnused.class) - .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) - .verify(); + EqualsVerifier.forClass(OneFieldUnused.class).suppress(Warning.ALL_FIELDS_SHOULD_BE_USED).verify(); } @Test public void fail_whenAFieldIsUnused() { ExpectedException - .when(() -> EqualsVerifier.forClass(OneFieldUnused.class).verify()) - .assertFailure() - .assertMessageContains("Significant fields", "equals does not use", "colorNotUsed"); + .when(() -> EqualsVerifier.forClass(OneFieldUnused.class).verify()) + .assertFailure() + .assertMessageContains("Significant fields", "equals does not use", "colorNotUsed"); } @Test public void fail_whenANonfinalFieldIsUnused() { ExpectedException - .when(() -> EqualsVerifier.forClass(OneNonfinalFieldUnused.class).verify()) - .assertFailure() - .assertMessageContains("Significant fields", "equals does not use", "colorNotUsed"); + .when(() -> EqualsVerifier.forClass(OneNonfinalFieldUnused.class).verify()) + .assertFailure() + .assertMessageContains("Significant fields", "equals does not use", "colorNotUsed"); } @Test public void succeed_whenANonfinalFieldIsUnused_givenAllNonfinalFieldsWarningIsSuppressed() { EqualsVerifier - .forClass(OneNonfinalFieldUnused.class) - .suppress(Warning.ALL_NONFINAL_FIELDS_SHOULD_BE_USED) - .verify(); + .forClass(OneNonfinalFieldUnused.class) + .suppress(Warning.ALL_NONFINAL_FIELDS_SHOULD_BE_USED) + .verify(); } @Test public void fail_whenAFieldIsUnused_givenOnlyAllNonfinalFieldsWarningIsSuppressed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(OneFieldUnused.class) - .suppress(Warning.ALL_NONFINAL_FIELDS_SHOULD_BE_USED) - .verify() - ) - .assertFailure() - .assertMessageContains("Significant fields", "equals does not use", "colorNotUsed"); + .when( + () -> EqualsVerifier + .forClass(OneFieldUnused.class) + .suppress(Warning.ALL_NONFINAL_FIELDS_SHOULD_BE_USED) + .verify()) + .assertFailure() + .assertMessageContains("Significant fields", "equals does not use", "colorNotUsed"); } @Test @@ -144,26 +118,23 @@ public void succeed_whenAStaticFieldIsUnused_givenAllFieldsShouldBeUsed() { @Test public void succeed_whenAFieldIsUnusedInASubclass_givenAllFieldsWarningIsSuppressed() { - EqualsVerifier - .forClass(OneFieldUnusedExtended.class) - .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) - .verify(); + EqualsVerifier.forClass(OneFieldUnusedExtended.class).suppress(Warning.ALL_FIELDS_SHOULD_BE_USED).verify(); } @Test public void fail_whenAFieldIsUnusedInASubclass() { ExpectedException - .when(() -> EqualsVerifier.forClass(OneFieldUnusedExtended.class).verify()) - .assertFailure() - .assertMessageContains("Significant fields", "equals does not use", "colorNotUsed"); + .when(() -> EqualsVerifier.forClass(OneFieldUnusedExtended.class).verify()) + .assertFailure() + .assertMessageContains("Significant fields", "equals does not use", "colorNotUsed"); } @Test public void succeed_whenNoEqualsMethodPresent_givenAllFieldsWarningIsSuppressed() { EqualsVerifier - .forClass(NoFieldsUsed.class) - .suppress(Warning.INHERITED_DIRECTLY_FROM_OBJECT, Warning.ALL_FIELDS_SHOULD_BE_USED) - .verify(); + .forClass(NoFieldsUsed.class) + .suppress(Warning.INHERITED_DIRECTLY_FROM_OBJECT, Warning.ALL_FIELDS_SHOULD_BE_USED) + .verify(); } @Test @@ -174,28 +145,26 @@ public void succeed_whenNoFieldsAreAdded_givenAllFieldsShouldBeUsed() { @Test public void fail_whenNoFieldsAreUsed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(NoFieldsUsed.class) - .suppress(Warning.INHERITED_DIRECTLY_FROM_OBJECT) - .verify() - ) - .assertFailure() - .assertMessageContains("Significant fields", "equals does not use", "color"); + .when( + () -> EqualsVerifier + .forClass(NoFieldsUsed.class) + .suppress(Warning.INHERITED_DIRECTLY_FROM_OBJECT) + .verify()) + .assertFailure() + .assertMessageContains("Significant fields", "equals does not use", "color"); } @Test public void fail_whenNoFieldsAreUsed_givenUsingGetClass() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(NoFieldsUsed.class) - .suppress(Warning.INHERITED_DIRECTLY_FROM_OBJECT) - .usingGetClass() - .verify() - ) - .assertFailure() - .assertMessageContains("Significant fields", "equals does not use", "color"); + .when( + () -> EqualsVerifier + .forClass(NoFieldsUsed.class) + .suppress(Warning.INHERITED_DIRECTLY_FROM_OBJECT) + .usingGetClass() + .verify()) + .assertFailure() + .assertMessageContains("Significant fields", "equals does not use", "color"); } @Test @@ -206,101 +175,77 @@ public void succeed_whenAFieldIsUnused_givenAllFieldsShouldBeUsedExceptThatField @Test public void succeed_whenTwoFieldsAreUnused_givenAllFieldsShouldBeUsedExceptThoseTwo() { EqualsVerifier - .forClass(TwoFieldsUnusedColorPoint.class) - .withIgnoredFields("colorNotUsed", "colorAlsoNotUsed") - .verify(); + .forClass(TwoFieldsUnusedColorPoint.class) + .withIgnoredFields("colorNotUsed", "colorAlsoNotUsed") + .verify(); } @Test public void succeed_whenRepeatingWithIgnoredFields_givenAllFieldsShouldBeUsedExceptThoseTwo() { EqualsVerifier - .forClass(TwoFieldsUnusedColorPoint.class) - .withIgnoredFields("colorNotUsed") - .withIgnoredFields("colorAlsoNotUsed") - .verify(); + .forClass(TwoFieldsUnusedColorPoint.class) + .withIgnoredFields("colorNotUsed") + .withIgnoredFields("colorAlsoNotUsed") + .verify(); } @Test public void succeed_whenRepeatingWithOnlyTheseFields_givenAllFieldsShouldBeUsedExceptThoseTwo() { - EqualsVerifier - .forClass(OneFieldUnused.class) - .withOnlyTheseFields("x") - .withOnlyTheseFields("y") - .verify(); + EqualsVerifier.forClass(OneFieldUnused.class).withOnlyTheseFields("x").withOnlyTheseFields("y").verify(); } @Test public void fail_whenCombiningWithOnlyTheseFieldsAndWithIgnoredFields() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(OneFieldUnused.class) - .withOnlyTheseFields("x", "y") - .withIgnoredFields("colorNotUsed") - .verify() - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "Precondition", - "you can call either withOnlyTheseFields or withIgnoredFields, but not both." - ); + .when( + () -> EqualsVerifier + .forClass(OneFieldUnused.class) + .withOnlyTheseFields("x", "y") + .withIgnoredFields("colorNotUsed") + .verify()) + .assertThrows(IllegalStateException.class) + .assertMessageContains( + "Precondition", + "you can call either withOnlyTheseFields or withIgnoredFields, but not both."); } @Test public void fail_whenTwoFieldsAreUnUsed_givenAllFieldsShouldBeUsedExceptOneOfThemButNotBoth() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(TwoFieldsUnusedColorPoint.class) - .withIgnoredFields("colorNotUsed") - .verify() - ) - .assertFailure() - .assertMessageContains("Significant fields", "equals does not use", "colorAlsoNotUsed"); + .when( + () -> EqualsVerifier + .forClass(TwoFieldsUnusedColorPoint.class) + .withIgnoredFields("colorNotUsed") + .verify()) + .assertFailure() + .assertMessageContains("Significant fields", "equals does not use", "colorAlsoNotUsed"); } @Test public void fail_whenAllFieldsAreUsed_givenAllFieldsShouldBeUsedExceptOneThatActuallyIsUsed() { ExpectedException - .when(() -> EqualsVerifier.forClass(FinalPoint.class).withIgnoredFields("x").verify()) - .assertFailure() - .assertMessageContains( - "Significant fields", - "equals should not use", - "x", - "but it does" - ); + .when(() -> EqualsVerifier.forClass(FinalPoint.class).withIgnoredFields("x").verify()) + .assertFailure() + .assertMessageContains("Significant fields", "equals should not use", "x", "but it does"); } @Test public void fail_whenOneFieldIsUnused_givenAllFieldsShouldBeUsedExceptTwoFields() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(OneFieldUnused.class) - .withIgnoredFields("x", "colorNotUsed") - .verify() - ) - .assertFailure() - .assertMessageContains( - "Significant fields", - "equals should not use", - "x", - "but it does" - ); + .when( + () -> EqualsVerifier.forClass(OneFieldUnused.class).withIgnoredFields("x", "colorNotUsed").verify()) + .assertFailure() + .assertMessageContains("Significant fields", "equals should not use", "x", "but it does"); } @Test public void anExceptionIsThrown_whenANonExistingFieldIsExcepted() { ExpectedException - .when(() -> - EqualsVerifier.forClass(FinalPoint.class).withIgnoredFields("thisFieldDoesNotExist") - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "Precondition", - "class FinalPoint does not contain field thisFieldDoesNotExist." - ); + .when(() -> EqualsVerifier.forClass(FinalPoint.class).withIgnoredFields("thisFieldDoesNotExist")) + .assertThrows(IllegalStateException.class) + .assertMessageContains( + "Precondition", + "class FinalPoint does not contain field thisFieldDoesNotExist."); } @Test @@ -311,158 +256,118 @@ public void succeed_whenAFieldIsUnused_givenTheUsedFieldsAreSpecified() { @Test public void fail_whenAllFieldsAreUsed_givenTheUsedFieldsAreSpecifiedButWeMissedOne() { ExpectedException - .when(() -> EqualsVerifier.forClass(FinalPoint.class).withOnlyTheseFields("x").verify()) - .assertFailure() - .assertMessageContains( - "Significant fields", - "equals should not use", - "y", - "but it does" - ); + .when(() -> EqualsVerifier.forClass(FinalPoint.class).withOnlyTheseFields("x").verify()) + .assertFailure() + .assertMessageContains("Significant fields", "equals should not use", "y", "but it does"); } @Test public void fail_whenAFieldIsUnused_givenTheUnusedFieldIsAlsoSpecified() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(OneFieldUnused.class) - .withOnlyTheseFields("x", "y", "colorNotUsed") - .verify() - ) - .assertFailure() - .assertMessageContains("Significant fields", "equals does not use", "colorNotUsed"); + .when( + () -> EqualsVerifier + .forClass(OneFieldUnused.class) + .withOnlyTheseFields("x", "y", "colorNotUsed") + .verify()) + .assertFailure() + .assertMessageContains("Significant fields", "equals does not use", "colorNotUsed"); } @Test public void anExceptionIsThrown_whenANonExistingFieldIsSpecified() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(FinalPoint.class) - .withOnlyTheseFields("thisFieldDoesNotExist") - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "Precondition", - "class FinalPoint does not contain field thisFieldDoesNotExist." - ); + .when(() -> EqualsVerifier.forClass(FinalPoint.class).withOnlyTheseFields("thisFieldDoesNotExist")) + .assertThrows(IllegalStateException.class) + .assertMessageContains( + "Precondition", + "class FinalPoint does not contain field thisFieldDoesNotExist."); } @Test public void anExceptionIsThrown_whenIgnoredFieldsOverlapWithSpecifiedFields() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(FinalPoint.class) - .withOnlyTheseFields("x") - .withIgnoredFields("x") - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "Precondition", - "you can call either withOnlyTheseFields or withIgnoredFields, but not both." - ); + .when(() -> EqualsVerifier.forClass(FinalPoint.class).withOnlyTheseFields("x").withIgnoredFields("x")) + .assertThrows(IllegalStateException.class) + .assertMessageContains( + "Precondition", + "you can call either withOnlyTheseFields or withIgnoredFields, but not both."); } @Test public void anExceptionIsThrown_whenSpecifiedFieldsOverlapWithIgnoredFields() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(FinalPoint.class) - .withIgnoredFields("x") - .withOnlyTheseFields("x") - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "Precondition", - "you can call either withOnlyTheseFields or withIgnoredFields, but not both." - ); + .when(() -> EqualsVerifier.forClass(FinalPoint.class).withIgnoredFields("x").withOnlyTheseFields("x")) + .assertThrows(IllegalStateException.class) + .assertMessageContains( + "Precondition", + "you can call either withOnlyTheseFields or withIgnoredFields, but not both."); } @Test public void succeed_whenAUsedFieldHasUnusedStaticFinalMembers_givenAllFieldsWarningIsSuppressed() { EqualsVerifier - .forClass(IndirectStaticFinalContainer.class) - .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) - .verify(); + .forClass(IndirectStaticFinalContainer.class) + .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) + .verify(); } @Test public void fail_whenUnusedFieldIsStateless() { ExpectedException - .when(() -> EqualsVerifier.forClass(UnusedStatelessContainer.class).verify()) - .assertFailure() - .assertMessageContains("Significant fields", "statelessField", "or it is stateless"); + .when(() -> EqualsVerifier.forClass(UnusedStatelessContainer.class).verify()) + .assertFailure() + .assertMessageContains("Significant fields", "statelessField", "or it is stateless"); } @Test public void succeed_whenUnusedFieldIsStateless_givenAllFieldsWarningIsSuppressed() { - EqualsVerifier - .forClass(UnusedStatelessContainer.class) - .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) - .verify(); + EqualsVerifier.forClass(UnusedStatelessContainer.class).suppress(Warning.ALL_FIELDS_SHOULD_BE_USED).verify(); } @Test public void fail_whenUsedFieldIsStateless() { ExpectedException - .when(() -> EqualsVerifier.forClass(UsedStatelessContainer.class).verify()) - .assertFailure() - .assertMessageContains("Significant fields", "statelessField", "or it is stateless"); + .when(() -> EqualsVerifier.forClass(UsedStatelessContainer.class).verify()) + .assertFailure() + .assertMessageContains("Significant fields", "statelessField", "or it is stateless"); } @Test public void succeed_whenUsedFieldIsStateless_givenAllFieldsWarningIsSuppressed() { - EqualsVerifier - .forClass(UsedStatelessContainer.class) - .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) - .verify(); + EqualsVerifier.forClass(UsedStatelessContainer.class).suppress(Warning.ALL_FIELDS_SHOULD_BE_USED).verify(); } @Test public void succeed_whenUsedFieldIsStateless_givenStatelessFieldIsIgnored() { - EqualsVerifier - .forClass(UsedStatelessContainer.class) - .withIgnoredFields("statelessField") - .verify(); + EqualsVerifier.forClass(UsedStatelessContainer.class).withIgnoredFields("statelessField").verify(); } @Test public void succeed_whenClassIsStateless_givenAllFieldsWarningIsSuppressed() { - EqualsVerifier - .forClass(Stateless.class) - .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) - .verify(); + EqualsVerifier.forClass(Stateless.class).suppress(Warning.ALL_FIELDS_SHOULD_BE_USED).verify(); } @Test public void fail_whenNonNullFieldIsEqualToNullField() { ExpectedException - .when(() -> EqualsVerifier.forClass(BugWhenFieldIsNull.class).verify()) - .assertFailure() - .assertMessageContains( - "Significant fields", - "hashCode relies on", - "s", - "equals does not", - "These objects are equal, but probably shouldn't be" - ); + .when(() -> EqualsVerifier.forClass(BugWhenFieldIsNull.class).verify()) + .assertFailure() + .assertMessageContains( + "Significant fields", + "hashCode relies on", + "s", + "equals does not", + "These objects are equal, but probably shouldn't be"); } @Test public void giveCorrectMessage_whenStaticFieldIsNotUsed_givenStaticFieldIsFirstField() { // See https://github.com/jqno/equalsverifier/issues/159 ExpectedException - .when(() -> - EqualsVerifier - .forClass(IdentityIntContainer.class) - .suppress(Warning.IDENTICAL_COPY) - .verify() - ) - .assertFailure() - .assertMessageContains("Significant fields", "equals does not use i"); + .when( + () -> EqualsVerifier.forClass(IdentityIntContainer.class).suppress(Warning.IDENTICAL_COPY).verify()) + .assertFailure() + .assertMessageContains("Significant fields", "equals does not use i"); } static final class ConstantHashCode { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/StringTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/StringTest.java index 7d36f6e28..c9e79d921 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/StringTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/StringTest.java @@ -1,6 +1,7 @@ package nl.jqno.equalsverifier.integration.extended_contract; import java.util.Objects; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.internal.checkers.fieldchecks.StringFieldCheck; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; @@ -11,15 +12,14 @@ public class StringTest { @Test public void fail_whenStringIsComparedUsingEqualsIgnoreCaseAndHashCodeIsCaseSensitive() { ExpectedException - .when(() -> EqualsVerifier.forClass(IncorrectIgnoreCaseStringEquals.class).verify()) - .assertFailure() - .assertMessageContains( - StringFieldCheck.ERROR_DOC_TITLE, - "equalsIgnoreCase", - "hashCode", - "toUpperCase()", - "String field caseInsensitiveString" - ); + .when(() -> EqualsVerifier.forClass(IncorrectIgnoreCaseStringEquals.class).verify()) + .assertFailure() + .assertMessageContains( + StringFieldCheck.ERROR_DOC_TITLE, + "equalsIgnoreCase", + "hashCode", + "toUpperCase()", + "String field caseInsensitiveString"); } @Test @@ -30,21 +30,16 @@ public void succeed_whenStringIsComparedUsingEqualsIgnoreCaseAndHashCodeIsAlsoCa @Test public void fail_whenStringIsComparedUsingEqualsIgnoreCaseAndHashCodeIsCaseSensitive_givenHashCodeIsCached() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(IncorrectCachedIgnoreCaseStringEquals.class) - .withCachedHashCode( - "cachedHashCode", - "calcHashCode", - new IncorrectCachedIgnoreCaseStringEquals("a") - ) - .verify() - ) - .assertFailure() - .assertMessageContains( - StringFieldCheck.ERROR_DOC_TITLE, - "String field caseInsensitiveString" - ); + .when( + () -> EqualsVerifier + .forClass(IncorrectCachedIgnoreCaseStringEquals.class) + .withCachedHashCode( + "cachedHashCode", + "calcHashCode", + new IncorrectCachedIgnoreCaseStringEquals("a")) + .verify()) + .assertFailure() + .assertMessageContains(StringFieldCheck.ERROR_DOC_TITLE, "String field caseInsensitiveString"); } private static final class IncorrectIgnoreCaseStringEquals { @@ -62,8 +57,8 @@ public boolean equals(Object obj) { } IncorrectIgnoreCaseStringEquals other = (IncorrectIgnoreCaseStringEquals) obj; return caseInsensitiveString == null - ? other.caseInsensitiveString == null - : caseInsensitiveString.equalsIgnoreCase(other.caseInsensitiveString); + ? other.caseInsensitiveString == null + : caseInsensitiveString.equalsIgnoreCase(other.caseInsensitiveString); } @Override @@ -87,15 +82,13 @@ public boolean equals(Object obj) { } CorrectIgnoreCaseStringEquals other = (CorrectIgnoreCaseStringEquals) obj; return caseInsensitiveString == null - ? other.caseInsensitiveString == null - : caseInsensitiveString.equalsIgnoreCase(other.caseInsensitiveString); + ? other.caseInsensitiveString == null + : caseInsensitiveString.equalsIgnoreCase(other.caseInsensitiveString); } @Override public int hashCode() { - return Objects.hash( - caseInsensitiveString == null ? "" : caseInsensitiveString.toUpperCase() - ); + return Objects.hash(caseInsensitiveString == null ? "" : caseInsensitiveString.toUpperCase()); } } @@ -114,11 +107,10 @@ public boolean equals(Object obj) { if (!(obj instanceof IncorrectCachedIgnoreCaseStringEquals)) { return false; } - IncorrectCachedIgnoreCaseStringEquals other = - (IncorrectCachedIgnoreCaseStringEquals) obj; + IncorrectCachedIgnoreCaseStringEquals other = (IncorrectCachedIgnoreCaseStringEquals) obj; return caseInsensitiveString == null - ? other.caseInsensitiveString == null - : caseInsensitiveString.equalsIgnoreCase(other.caseInsensitiveString); + ? other.caseInsensitiveString == null + : caseInsensitiveString.equalsIgnoreCase(other.caseInsensitiveString); } @Override diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/SyntheticFieldsTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/SyntheticFieldsTest.java index 20d7f1a21..8266a3e50 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/SyntheticFieldsTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/SyntheticFieldsTest.java @@ -5,6 +5,7 @@ import java.util.Comparator; import java.util.Objects; + import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/TransientFieldsTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/TransientFieldsTest.java index 015be0c84..b220d089c 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/TransientFieldsTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/TransientFieldsTest.java @@ -1,6 +1,7 @@ package nl.jqno.equalsverifier.integration.extended_contract; import java.util.Objects; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; @@ -17,33 +18,22 @@ public void succeed_whenFieldsWithTransientModifierAreNotUsedInEquals() { @Test public void fail_whenFieldsWithTransientModifierAreUsedInEquals() { ExpectedException - .when(() -> EqualsVerifier.forClass(UsingFieldsWithTransientModifier.class).verify()) - .assertFailure() - .assertMessageContains( - "Transient field", - "should not be included in equals/hashCode contract" - ); + .when(() -> EqualsVerifier.forClass(UsingFieldsWithTransientModifier.class).verify()) + .assertFailure() + .assertMessageContains("Transient field", "should not be included in equals/hashCode contract"); } @Test public void succeed_whenFieldsWithTransientModifierAreUsedInEquals_givenWarningsAreSuppressed() { - EqualsVerifier - .forClass(UsingFieldsWithTransientModifier.class) - .suppress(Warning.TRANSIENT_FIELDS) - .verify(); + EqualsVerifier.forClass(UsingFieldsWithTransientModifier.class).suppress(Warning.TRANSIENT_FIELDS).verify(); } @Test public void fail_whenFieldsWithTransientModifierAreUsedInEquals_givenTheyreDeclaredInSuperclass() { ExpectedException - .when(() -> - EqualsVerifier.forClass(SubclassUsingFieldsWithTransientModifier.class).verify() - ) - .assertFailure() - .assertMessageContains( - "Transient field", - "should not be included in equals/hashCode contract" - ); + .when(() -> EqualsVerifier.forClass(SubclassUsingFieldsWithTransientModifier.class).verify()) + .assertFailure() + .assertMessageContains("Transient field", "should not be included in equals/hashCode contract"); } @Test @@ -54,46 +44,30 @@ public void succeed_whenFieldsWithTransientAnnotationAreNotUsedInEquals() { @Test public void fail_whenFieldsWithTransientAnnotationAreUsedInEquals() { ExpectedException - .when(() -> EqualsVerifier.forClass(UsingFieldsWithTransientAnnotation.class).verify()) - .assertFailure() - .assertMessageContains( - "Transient field", - "should not be included in equals/hashCode contract" - ); + .when(() -> EqualsVerifier.forClass(UsingFieldsWithTransientAnnotation.class).verify()) + .assertFailure() + .assertMessageContains("Transient field", "should not be included in equals/hashCode contract"); } @Test public void succeed_whenFieldsWithTransientAnnotationAreUsedInEquals_givenWarningsAreSuppressed() { - EqualsVerifier - .forClass(UsingFieldsWithTransientAnnotation.class) - .suppress(Warning.TRANSIENT_FIELDS) - .verify(); + EqualsVerifier.forClass(UsingFieldsWithTransientAnnotation.class).suppress(Warning.TRANSIENT_FIELDS).verify(); } @Test public void fail_whenFieldsWithTransientAnnotationAreUsedInEquals_givenTheyreDeclaredInSuperclass() { ExpectedException - .when(() -> - EqualsVerifier.forClass(SubclassUsingFieldsWithTransientAnnotation.class).verify() - ) - .assertFailure() - .assertMessageContains( - "Transient field", - "should not be included in equals/hashCode contract" - ); + .when(() -> EqualsVerifier.forClass(SubclassUsingFieldsWithTransientAnnotation.class).verify()) + .assertFailure() + .assertMessageContains("Transient field", "should not be included in equals/hashCode contract"); } @Test public void fail_whenFieldsWithTransientAnnotationAreNotUsedInEquals_givenAnnotationIsNotAJpaAnnotation() { ExpectedException - .when(() -> - EqualsVerifier.forClass(NotUsingFieldsWithNonJpaTransientAnnotation.class).verify() - ) - .assertFailure() - .assertMessageContains( - "Significant fields", - "equals does not use j, or it is stateless" - ); + .when(() -> EqualsVerifier.forClass(NotUsingFieldsWithNonJpaTransientAnnotation.class).verify()) + .assertFailure() + .assertMessageContains("Significant fields", "equals does not use j, or it is stateless"); } static class NotUsingFieldsWithTransientModifier { @@ -170,8 +144,7 @@ public final boolean equals(Object obj) { if (!(obj instanceof NotUsingFieldsWithTransientAnnotation)) { return false; } - NotUsingFieldsWithTransientAnnotation other = - (NotUsingFieldsWithTransientAnnotation) obj; + NotUsingFieldsWithTransientAnnotation other = (NotUsingFieldsWithTransientAnnotation) obj; return i == other.i; } @@ -208,8 +181,7 @@ public final int hashCode() { } } - static class SubclassUsingFieldsWithTransientAnnotation - extends UsingFieldsWithTransientAnnotation { + static class SubclassUsingFieldsWithTransientAnnotation extends UsingFieldsWithTransientAnnotation { public SubclassUsingFieldsWithTransientAnnotation(int i, int j) { super(i, j); @@ -233,8 +205,7 @@ public final boolean equals(Object obj) { if (!(obj instanceof NotUsingFieldsWithNonJpaTransientAnnotation)) { return false; } - NotUsingFieldsWithNonJpaTransientAnnotation other = - (NotUsingFieldsWithNonJpaTransientAnnotation) obj; + NotUsingFieldsWithNonJpaTransientAnnotation other = (NotUsingFieldsWithNonJpaTransientAnnotation) obj; return i == other.i; } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/TypeCheckTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/TypeCheckTest.java index 67009d15d..38abf68c9 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/TypeCheckTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extended_contract/TypeCheckTest.java @@ -9,29 +9,27 @@ public class TypeCheckTest { @Test public void fail_whenEqualsReturnsTrueForACompletelyUnrelatedType() { ExpectedException - .when(() -> EqualsVerifier.forClass(WrongTypeCheck.class).verify()) - .assertFailure() - .assertMessageContains("Type-check: equals returns true for an unrelated type."); + .when(() -> EqualsVerifier.forClass(WrongTypeCheck.class).verify()) + .assertFailure() + .assertMessageContains("Type-check: equals returns true for an unrelated type."); } @Test public void fail_whenEqualsDoesNotTypeCheck() { ExpectedException - .when(() -> EqualsVerifier.forClass(NoTypeCheck.class).verify()) - .assertFailure() - .assertCause(ClassCastException.class) - .assertMessageContains("Type-check: equals throws ClassCastException"); + .when(() -> EqualsVerifier.forClass(NoTypeCheck.class).verify()) + .assertFailure() + .assertCause(ClassCastException.class) + .assertMessageContains("Type-check: equals throws ClassCastException"); } @Test public void fail_whenEqualsDoesNotTypeCheckAndThrowsAnExceptionOtherThanClassCastException() { ExpectedException - .when(() -> - EqualsVerifier.forClass(NoTypeCheckButNoClassCastExceptionEither.class).verify() - ) - .assertFailure() - .assertCause(IllegalStateException.class) - .assertMessageContains("Type-check: equals throws IllegalStateException"); + .when(() -> EqualsVerifier.forClass(NoTypeCheckButNoClassCastExceptionEither.class).verify()) + .assertFailure() + .assertCause(IllegalStateException.class) + .assertMessageContains("Type-check: equals throws IllegalStateException"); } static final class WrongTypeCheck { @@ -86,7 +84,8 @@ public boolean equals(Object obj) { return false; } return i == ((NoTypeCheckButNoClassCastExceptionEither) obj).i; - } catch (ClassCastException e) { + } + catch (ClassCastException e) { throw new IllegalStateException(e); } } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/AnnotationImmutableTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/AnnotationImmutableTest.java index 29f97b647..fe4a44e79 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/AnnotationImmutableTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/AnnotationImmutableTest.java @@ -20,22 +20,17 @@ public void succeed_whenClassHasNonfinalFields_givenImmutableAnnotation() { @Test public void succeed_whenRedefinableClassHasNonfinalFields_givenImmutableAnnotationAndAppropriateSubclass() { EqualsVerifier - .forClass(ImmutableCanEqualPoint.class) - .withRedefinedSubclass(MutableCanEqualColorPoint.class) - .verify(); + .forClass(ImmutableCanEqualPoint.class) + .withRedefinedSubclass(MutableCanEqualColorPoint.class) + .verify(); } @Test public void fail_whenSuperclassHasImmutableAnnotationButThisClassDoesnt() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(MutableCanEqualColorPoint.class) - .withRedefinedSuperclass() - .verify() - ) - .assertFailure() - .assertMessageContains("Mutability", "equals depends on mutable field", "color"); + .when(() -> EqualsVerifier.forClass(MutableCanEqualColorPoint.class).withRedefinedSuperclass().verify()) + .assertFailure() + .assertMessageContains("Mutability", "equals depends on mutable field", "color"); } @Immutable diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/AnnotationNonnullEclipseTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/AnnotationNonnullEclipseTest.java index 31ac7e696..68aa4b001 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/AnnotationNonnullEclipseTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/AnnotationNonnullEclipseTest.java @@ -1,6 +1,7 @@ package nl.jqno.equalsverifier.integration.extra_features; import java.util.Objects; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.integration.extra_features.nonnull.eclipse.NonnullEclipseOnPackage; @@ -41,68 +42,46 @@ public void succeed_whenEqualsDoesntCheckForNull_givenEclipseDefaultAnnotationOn @Test public void fail_whenEqualsDoesntCheckForNull_givenEclipseDefaultAndNullableAnnotationOnClass() { ExpectedException - .when(() -> EqualsVerifier.forClass(NonnullEclipseWithNullableOnClass.class).verify()) - .assertFailure() - .assertMessageContains( - "Non-nullity", - "equals throws NullPointerException", - "'this' object's field o" - ); + .when(() -> EqualsVerifier.forClass(NonnullEclipseWithNullableOnClass.class).verify()) + .assertFailure() + .assertMessageContains("Non-nullity", "equals throws NullPointerException", "'this' object's field o"); } @Test public void succeed_whenEqualsDoesntCheckForNull_givenEclipseDefaultAndNullableAnnotationOnClassAndWarningSuppressed() { - EqualsVerifier - .forClass(NonnullEclipseWithNullableOnClass.class) - .suppress(Warning.NULL_FIELDS) - .verify(); + EqualsVerifier.forClass(NonnullEclipseWithNullableOnClass.class).suppress(Warning.NULL_FIELDS).verify(); } @Test public void succeed_whenEqualsChecksForNull_givenEclipseDefaultAndNullableAnnotationOnClass() { - EqualsVerifier - .forClass(NonnullEclipseWithNullableOnClassAndNullCheckInEquals.class) - .verify(); + EqualsVerifier.forClass(NonnullEclipseWithNullableOnClassAndNullCheckInEquals.class).verify(); } @Test public void fail_whenEqualsDoesntCheckForNull_givenEclipseDefaultAndNullableAnnotationOnPackage() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(NonnullEclipseWithNullableOnPackageAndNullCheckInEquals.class) - .verify() - ) - .assertFailure() - .assertMessageContains( - "Non-nullity", - "equals throws NullPointerException", - "'this' object's field o" - ); + .when( + () -> EqualsVerifier + .forClass(NonnullEclipseWithNullableOnPackageAndNullCheckInEquals.class) + .verify()) + .assertFailure() + .assertMessageContains("Non-nullity", "equals throws NullPointerException", "'this' object's field o"); } @Test public void succeed_whenEqualsDoesntCheckForNull_givenEclipseDefaultAndNullableAnnotationOnPackageAndWarningIsSuppressed() { EqualsVerifier - .forClass(NonnullEclipseWithNullableOnPackageAndNullCheckInEquals.class) - .suppress(Warning.NULL_FIELDS) - .verify(); + .forClass(NonnullEclipseWithNullableOnPackageAndNullCheckInEquals.class) + .suppress(Warning.NULL_FIELDS) + .verify(); } @Test public void fail_whenEqualsDoesntCheckForNull_givenEclipseDefaultAnnotationButInapplicableLocationOnClass() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(NonnullEclipseWithInapplicableLocationOnClass.class) - .verify() - ) - .assertFailure() - .assertMessageContains( - "Non-nullity", - "equals throws NullPointerException", - "'this' object's field o" - ); + .when(() -> EqualsVerifier.forClass(NonnullEclipseWithInapplicableLocationOnClass.class).verify()) + .assertFailure() + .assertMessageContains("Non-nullity", "equals throws NullPointerException", "'this' object's field o"); } @Test @@ -252,7 +231,7 @@ public final boolean equals(Object obj) { return false; } NonnullEclipseWithNullableOnClassAndNullCheckInEquals other = - (NonnullEclipseWithNullableOnClassAndNullCheckInEquals) obj; + (NonnullEclipseWithNullableOnClassAndNullCheckInEquals) obj; return o == null ? other.o == null : o.equals(other.o); } @@ -277,7 +256,7 @@ public final boolean equals(Object obj) { return false; } NonnullEclipseWithNullableOnPackageAndNullCheckInEquals other = - (NonnullEclipseWithNullableOnPackageAndNullCheckInEquals) obj; + (NonnullEclipseWithNullableOnPackageAndNullCheckInEquals) obj; return o.equals(other.o); } @@ -301,8 +280,7 @@ public boolean equals(Object obj) { if (!(obj instanceof NonnullEclipseWithInapplicableLocationOnClass)) { return false; } - NonnullEclipseWithInapplicableLocationOnClass other = - (NonnullEclipseWithInapplicableLocationOnClass) obj; + NonnullEclipseWithInapplicableLocationOnClass other = (NonnullEclipseWithInapplicableLocationOnClass) obj; return o.equals(other.o); } @@ -326,8 +304,7 @@ public boolean equals(Object obj) { if (!(obj instanceof NonnullEclipseWithApplicableLocationOnClass)) { return false; } - NonnullEclipseWithApplicableLocationOnClass other = - (NonnullEclipseWithApplicableLocationOnClass) obj; + NonnullEclipseWithApplicableLocationOnClass other = (NonnullEclipseWithApplicableLocationOnClass) obj; return o.equals(other.o); } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/AnnotationNonnullTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/AnnotationNonnullTest.java index 5be4a84f0..f0b9d04da 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/AnnotationNonnullTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/AnnotationNonnullTest.java @@ -5,6 +5,7 @@ import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.integration.extra_features.nonnull.findbugs1x.custom.NonnullFindbugs1xCustomOnPackage; @@ -30,14 +31,13 @@ public void succeed_whenEqualsDoesntCheckForNull_givenFieldsHaveNonnullAnnotatio @Test public void fail_whenEqualsDoesntCheckForNull_givenFieldsHaveNonnullAnnotationButOneDoesnt() { ExpectedException - .when(() -> EqualsVerifier.forClass(NonnullManualMissedOne.class).verify()) - .assertFailure() - .assertCause(NullPointerException.class) - .assertMessageContains( - "Non-nullity", - "equals throws NullPointerException", - "'this' object's field noAnnotation" - ); + .when(() -> EqualsVerifier.forClass(NonnullManualMissedOne.class).verify()) + .assertFailure() + .assertCause(NullPointerException.class) + .assertMessageContains( + "Non-nullity", + "equals throws NullPointerException", + "'this' object's field noAnnotation"); } @Test @@ -58,17 +58,17 @@ public void succeed_whenEqualsDoesntCheckForNull_givenFindbugs1xDefaultAnnotatio @Test public void fail_whenEqualsDoesntCheckForNull_givenEmptyFindbugs1xDefaultAnnotationOnClass() { ExpectedException - .when(() -> EqualsVerifier.forClass(EmptyFindbugs1xCustomOnClass.class).verify()) - .assertFailure() - .assertMessageContains("Non-nullity"); + .when(() -> EqualsVerifier.forClass(EmptyFindbugs1xCustomOnClass.class).verify()) + .assertFailure() + .assertMessageContains("Non-nullity"); } @Test public void fail_whenEqualsDoesntCheckForNull_givenFindbugs1xDefaultAnnotationWithoutNonnullAnnotationOnClass() { ExpectedException - .when(() -> EqualsVerifier.forClass(NotNonnullFindbugs1xCustomOnClass.class).verify()) - .assertFailure() - .assertMessageContains("Non-nullity"); + .when(() -> EqualsVerifier.forClass(NotNonnullFindbugs1xCustomOnClass.class).verify()) + .assertFailure() + .assertMessageContains("Non-nullity"); } @Test @@ -89,13 +89,9 @@ public void succeed_whenEqualsDoesntCheckForNull_givenFindbugs1xDefaultAnnotatio @Test public void fail_whenEqualsDoesntCheckForNull_givenFindbugs1xDefaultAnnotationForParameters() { ExpectedException - .when(() -> EqualsVerifier.forClass(NonnullFindbugs1xForParameters.class).verify()) - .assertFailure() - .assertMessageContains( - "Non-nullity", - "equals throws NullPointerException", - "'this' object's field o" - ); + .when(() -> EqualsVerifier.forClass(NonnullFindbugs1xForParameters.class).verify()) + .assertFailure() + .assertMessageContains("Non-nullity", "equals throws NullPointerException", "'this' object's field o"); } @Test @@ -111,71 +107,46 @@ public void succeed_whenEqualsDoesntCheckForNull_givenFindbugs1xDefaultAnnotatio @Test public void fail_whenEqualsDoesntCheckForNull_givenFindbugs1xDefaultAndNullableAnnotationOnClass() { ExpectedException - .when(() -> EqualsVerifier.forClass(NonnullFindbugs1xWithNullableOnClass.class).verify() - ) - .assertFailure() - .assertMessageContains( - "Non-nullity", - "equals throws NullPointerException", - "'this' object's field p" - ); + .when(() -> EqualsVerifier.forClass(NonnullFindbugs1xWithNullableOnClass.class).verify()) + .assertFailure() + .assertMessageContains("Non-nullity", "equals throws NullPointerException", "'this' object's field p"); } @Test public void fail_whenEqualsDoesntCheckForNull_givenFindbugs1xDefaultAndCheckForNullAnnotationOnClass() { ExpectedException - .when(() -> - EqualsVerifier.forClass(NonnullFindbugs1xWithCheckForNullOnClass.class).verify() - ) - .assertFailure() - .assertMessageContains( - "Non-nullity", - "equals throws NullPointerException", - "'this' object's field p" - ); + .when(() -> EqualsVerifier.forClass(NonnullFindbugs1xWithCheckForNullOnClass.class).verify()) + .assertFailure() + .assertMessageContains("Non-nullity", "equals throws NullPointerException", "'this' object's field p"); } @Test public void fail_whenEqualsDoesntCheckForNull_givenFindbugs1xDefaultAndNullableAnnotationOnPackage() { ExpectedException - .when(() -> - EqualsVerifier.forClass(NonnullFindbugs1xWithNullableOnPackage.class).verify() - ) - .assertFailure() - .assertMessageContains( - "Non-nullity", - "equals throws NullPointerException", - "'this' object's field p" - ); + .when(() -> EqualsVerifier.forClass(NonnullFindbugs1xWithNullableOnPackage.class).verify()) + .assertFailure() + .assertMessageContains("Non-nullity", "equals throws NullPointerException", "'this' object's field p"); } @Test public void fail_whenEqualsDoesntCheckForNull_givenFindbugs1xDefaultAndCheckForNullAnnotationOnPackage() { ExpectedException - .when(() -> - EqualsVerifier.forClass(NonnullFindbugs1xWithCheckForNullOnPackage.class).verify() - ) - .assertFailure() - .assertMessageContains( - "Non-nullity", - "equals throws NullPointerException", - "'this' object's field p" - ); + .when(() -> EqualsVerifier.forClass(NonnullFindbugs1xWithCheckForNullOnPackage.class).verify()) + .assertFailure() + .assertMessageContains("Non-nullity", "equals throws NullPointerException", "'this' object's field p"); } @Test public void succeed_whenEqualsDoenstCheckForNull_givenJsr305DefaultAndCheckForNullOnPackageAndWarningSuppressed() { EqualsVerifier - .forClass(NonnullFindbugs1xWithCheckForNullOnPackage.class) - .suppress(Warning.NULL_FIELDS) - .verify(); + .forClass(NonnullFindbugs1xWithCheckForNullOnPackage.class) + .suppress(Warning.NULL_FIELDS) + .verify(); } @Test public void succeed_whenEqualsChecksForNull_givenJsr305DefaultAndNullableAnnotationOnClass() { - EqualsVerifier - .forClass(NonnullFindbugs1xWithNullableOnClassAndNullCheckInEquals.class) - .verify(); + EqualsVerifier.forClass(NonnullFindbugs1xWithNullableOnClassAndNullCheckInEquals.class).verify(); } @Test @@ -191,13 +162,9 @@ public void succeed_whenEqualsDoesntCheckForNull_givenJsr305DefaultAnnotationWit @Test public void fail_whenEqualsDoesntCheckForNull_givenJsr305DefaultAnnotationWithInapplicableTypeQualifierDefaultOnClass() { ExpectedException - .when(() -> EqualsVerifier.forClass(NonnullJsr305InapplicableOnClass.class).verify()) - .assertFailure() - .assertMessageContains( - "Non-nullity", - "equals throws NullPointerException", - "'this' object's field o" - ); + .when(() -> EqualsVerifier.forClass(NonnullJsr305InapplicableOnClass.class).verify()) + .assertFailure() + .assertMessageContains("Non-nullity", "equals throws NullPointerException", "'this' object's field o"); } @Test @@ -213,25 +180,17 @@ public void succeed_whenEqualsDoesntCheckForNull_givenJsr305DefaultAnnotationWit @Test public void succeed_whenEqualsDoesntCheckForNull_givenJsr305DefaultAnnotationWithInapplicableTypeQualifierDefaultOnPackage() { ExpectedException - .when(() -> EqualsVerifier.forClass(NonnullJsr305InapplicableOnPackage.class).verify()) - .assertFailure() - .assertMessageContains( - "Non-nullity", - "equals throws NullPointerException", - "'this' object's field o" - ); + .when(() -> EqualsVerifier.forClass(NonnullJsr305InapplicableOnPackage.class).verify()) + .assertFailure() + .assertMessageContains("Non-nullity", "equals throws NullPointerException", "'this' object's field o"); } @Test public void fail_whenEqualsDoesntCheckForNull_givenJsr305DefaultAndNullableAnnotationOnClass() { ExpectedException - .when(() -> EqualsVerifier.forClass(NonnullJsr305WithNullableOnClass.class).verify()) - .assertFailure() - .assertMessageContains( - "Non-nullity", - "equals throws NullPointerException", - "'this' object's field p" - ); + .when(() -> EqualsVerifier.forClass(NonnullJsr305WithNullableOnClass.class).verify()) + .assertFailure() + .assertMessageContains("Non-nullity", "equals throws NullPointerException", "'this' object's field p"); } @Test @@ -247,55 +206,35 @@ public void succeed_whenEqualsDoesntCheckForNull_givenJsr305DefaultAnnotationOnN @Test public void fail_whenEqualsDoesntCheckForNull_givenJsr305DefaultAndCheckForNullAnnotationOnClass() { ExpectedException - .when(() -> EqualsVerifier.forClass(NonnullJsr305WithCheckForNullOnClass.class).verify() - ) - .assertFailure() - .assertMessageContains( - "Non-nullity", - "equals throws NullPointerException", - "'this' object's field p" - ); + .when(() -> EqualsVerifier.forClass(NonnullJsr305WithCheckForNullOnClass.class).verify()) + .assertFailure() + .assertMessageContains("Non-nullity", "equals throws NullPointerException", "'this' object's field p"); } @Test public void fail_whenEqualsDoesntCheckForNull_givenJsr305DefaultAndNullableAnnotationOnPackage() { ExpectedException - .when(() -> EqualsVerifier.forClass(NonnullJsr305WithNullableOnPackage.class).verify()) - .assertFailure() - .assertMessageContains( - "Non-nullity", - "equals throws NullPointerException", - "'this' object's field p" - ); + .when(() -> EqualsVerifier.forClass(NonnullJsr305WithNullableOnPackage.class).verify()) + .assertFailure() + .assertMessageContains("Non-nullity", "equals throws NullPointerException", "'this' object's field p"); } @Test public void fail_whenEqualsDoesntCheckForNull_givenJsr305DefaultAndCheckForNullAnnotationOnPackage() { ExpectedException - .when(() -> - EqualsVerifier.forClass(NonnullJsr305WithCheckForNullOnPackage.class).verify() - ) - .assertFailure() - .assertMessageContains( - "Non-nullity", - "equals throws NullPointerException", - "'this' object's field p" - ); + .when(() -> EqualsVerifier.forClass(NonnullJsr305WithCheckForNullOnPackage.class).verify()) + .assertFailure() + .assertMessageContains("Non-nullity", "equals throws NullPointerException", "'this' object's field p"); } @Test public void succeed_whenEqualsDoenstCheckForNull_givenJsr305DefaultAndNullableOnPackageAndWarningSuppressed() { - EqualsVerifier - .forClass(NonnullJsr305WithNullableOnPackage.class) - .suppress(Warning.NULL_FIELDS) - .verify(); + EqualsVerifier.forClass(NonnullJsr305WithNullableOnPackage.class).suppress(Warning.NULL_FIELDS).verify(); } @Test public void succeed_whenEqualsChecksForNull_givenJsr305DefaultAndCheckForNullAnnotationOnClass() { - EqualsVerifier - .forClass(NonnullJsr305WithCheckForNullOnClassAndNullCheckInEquals.class) - .verify(); + EqualsVerifier.forClass(NonnullJsr305WithCheckForNullOnClassAndNullCheckInEquals.class).verify(); } static class NonnullManual { @@ -360,9 +299,7 @@ public boolean equals(Object obj) { return false; } NonnullManualMissedOne other = (NonnullManualMissedOne) obj; - return ( - o.equals(other.o) && noAnnotation.equals(other.noAnnotation) && q.equals(other.q) - ); + return o.equals(other.o) && noAnnotation.equals(other.noAnnotation) && q.equals(other.q); } @Override @@ -614,8 +551,7 @@ public boolean equals(Object obj) { if (!(obj instanceof NonnullFindbugs1xWithCheckForNullOnClass)) { return false; } - NonnullFindbugs1xWithCheckForNullOnClass other = - (NonnullFindbugs1xWithCheckForNullOnClass) obj; + NonnullFindbugs1xWithCheckForNullOnClass other = (NonnullFindbugs1xWithCheckForNullOnClass) obj; return o.equals(other.o) && p.equals(other.p); } @@ -644,7 +580,7 @@ public boolean equals(Object obj) { return false; } NonnullFindbugs1xWithNullableOnClassAndNullCheckInEquals other = - (NonnullFindbugs1xWithNullableOnClassAndNullCheckInEquals) obj; + (NonnullFindbugs1xWithNullableOnClassAndNullCheckInEquals) obj; return o.equals(other.o) && (p == null ? other.p == null : p.equals(other.p)); } @@ -854,7 +790,7 @@ public boolean equals(Object obj) { return false; } NonnullJsr305WithCheckForNullOnClassAndNullCheckInEquals other = - (NonnullJsr305WithCheckForNullOnClassAndNullCheckInEquals) obj; + (NonnullJsr305WithCheckForNullOnClassAndNullCheckInEquals) obj; return o.equals(other.o) && (p == null ? other.p == null : p.equals(other.p)); } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/AnnotationNullMarkedTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/AnnotationNullMarkedTest.java index 10706096b..e9e3b0670 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/AnnotationNullMarkedTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/AnnotationNullMarkedTest.java @@ -1,6 +1,7 @@ package nl.jqno.equalsverifier.integration.extra_features; import java.util.Objects; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.integration.extra_features.nonnull.jspecify.NullMarkedOnPackage; @@ -34,21 +35,14 @@ public void succeed_whenEqualsDoesntCheckForNull_givenNullMarkedAnnotationOnNest @Test public void fail_whenEqualsDoesntCheckForNull_givenNullMarkedAndNullableAnnotationOnClass() { ExpectedException - .when(() -> EqualsVerifier.forClass(NullMarkedWithNullableOnClass.class).verify()) - .assertFailure() - .assertMessageContains( - "Non-nullity", - "equals throws NullPointerException", - "'this' object's field o" - ); + .when(() -> EqualsVerifier.forClass(NullMarkedWithNullableOnClass.class).verify()) + .assertFailure() + .assertMessageContains("Non-nullity", "equals throws NullPointerException", "'this' object's field o"); } @Test public void succeed_whenEqualsDoesntCheckForNull_givenNullMarkedAndNullableAnnotationOnClassAndWarningSuppressed() { - EqualsVerifier - .forClass(NullMarkedWithNullableOnClass.class) - .suppress(Warning.NULL_FIELDS) - .verify(); + EqualsVerifier.forClass(NullMarkedWithNullableOnClass.class).suppress(Warning.NULL_FIELDS).verify(); } @Test @@ -174,7 +168,7 @@ public final boolean equals(Object obj) { return false; } NullMarkedWithNullableOnClassAndNullCheckInEquals other = - (NullMarkedWithNullableOnClassAndNullCheckInEquals) obj; + (NullMarkedWithNullableOnClassAndNullCheckInEquals) obj; return o == null ? other.o == null : o.equals(other.o); } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/AnnotationParametersAreNonnullByDefaultTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/AnnotationParametersAreNonnullByDefaultTest.java index d25957e5a..65c8f535c 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/AnnotationParametersAreNonnullByDefaultTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/AnnotationParametersAreNonnullByDefaultTest.java @@ -3,6 +3,7 @@ import java.util.Objects; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.integration.extra_features.nonnull.jsr305.parametersarenonnullbydefault.ParametersAreNonnullByDefaultOnPackage; @@ -28,40 +29,28 @@ public void succeed_whenEqualsDoesntCheckForNull_givenEclipseDefaultAnnotationOn @Test public void succeed_whenEqualsDoesntCheckForNull_givenEclipseDefaultAnnotationOnNestedOuterClass() { - EqualsVerifier - .forClass(ParametersAreNonnullByDefaultOuter.FMiddle.FInnerInner.class) - .verify(); + EqualsVerifier.forClass(ParametersAreNonnullByDefaultOuter.FMiddle.FInnerInner.class).verify(); } @Test public void fail_whenEqualsDoesntCheckForNull_givenEclipseDefaultAndNullableAnnotationOnClass() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(ParametersAreNonnullByDefaultWithNullableOnClass.class) - .verify() - ) - .assertFailure() - .assertMessageContains( - "Non-nullity", - "equals throws NullPointerException", - "'this' object's field o" - ); + .when(() -> EqualsVerifier.forClass(ParametersAreNonnullByDefaultWithNullableOnClass.class).verify()) + .assertFailure() + .assertMessageContains("Non-nullity", "equals throws NullPointerException", "'this' object's field o"); } @Test public void succeed_whenEqualsDoesntCheckForNull_givenEclipseDefaultAndNullableAnnotationOnClassAndWarningSuppressed() { EqualsVerifier - .forClass(ParametersAreNonnullByDefaultWithNullableOnClass.class) - .suppress(Warning.NULL_FIELDS) - .verify(); + .forClass(ParametersAreNonnullByDefaultWithNullableOnClass.class) + .suppress(Warning.NULL_FIELDS) + .verify(); } @Test public void succeed_whenEqualsChecksForNull_givenEclipseDefaultAndNullableAnnotationOnClass() { - EqualsVerifier - .forClass(ParamsNonnullByDefaultWithNullableOnClassAndNullCheckInEquals.class) - .verify(); + EqualsVerifier.forClass(ParamsNonnullByDefaultWithNullableOnClassAndNullCheckInEquals.class).verify(); } @ParametersAreNonnullByDefault @@ -157,7 +146,7 @@ public final boolean equals(Object obj) { return false; } ParametersAreNonnullByDefaultWithNullableOnClass other = - (ParametersAreNonnullByDefaultWithNullableOnClass) obj; + (ParametersAreNonnullByDefaultWithNullableOnClass) obj; return o.equals(other.o); } @@ -183,7 +172,7 @@ public final boolean equals(Object obj) { return false; } ParamsNonnullByDefaultWithNullableOnClassAndNullCheckInEquals other = - (ParamsNonnullByDefaultWithNullableOnClassAndNullCheckInEquals) obj; + (ParamsNonnullByDefaultWithNullableOnClassAndNullCheckInEquals) obj; return o == null ? other.o == null : o.equals(other.o); } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/AnnotationsIgnoreTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/AnnotationsIgnoreTest.java index 90af0c76d..591c1830f 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/AnnotationsIgnoreTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/AnnotationsIgnoreTest.java @@ -16,60 +16,49 @@ public class AnnotationsIgnoreTest { @Test public void fail_whenClassHasNonfinalFieldsAndImmutableAnnotation_givenImmutableAnnotationIsIgnored() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(ImmutableByAnnotation.class) - .withIgnoredAnnotations(Immutable.class) - .verify() - ) - .assertFailure() - .assertMessageContains("Mutability"); + .when( + () -> EqualsVerifier + .forClass(ImmutableByAnnotation.class) + .withIgnoredAnnotations(Immutable.class) + .verify()) + .assertFailure() + .assertMessageContains("Mutability"); } @Test public void fail_whenIgnoringNonnullAnnotation_givenNonnullIsIndirectlyAppliedThroughDefaultAnnotation() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(DefaultAnnotationNonnull.class) - .withIgnoredAnnotations(Nonnull.class) - .verify() - ) - .assertFailure() - .assertMessageContains("Non-nullity"); + .when( + () -> EqualsVerifier + .forClass(DefaultAnnotationNonnull.class) + .withIgnoredAnnotations(Nonnull.class) + .verify()) + .assertFailure() + .assertMessageContains("Non-nullity"); } @Test public void fail_whenIgnoringNonnullAnnotation_givenNonnullIsIndirectlyAppliedThroughJsr305() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(Jsr305Nonnull.class) - .withIgnoredAnnotations(Nonnull.class) - .verify() - ) - .assertFailure() - .assertMessageContains("Non-nullity"); + .when(() -> EqualsVerifier.forClass(Jsr305Nonnull.class).withIgnoredAnnotations(Nonnull.class).verify()) + .assertFailure() + .assertMessageContains("Non-nullity"); } @Test public void succeed_whenClassHasNonfinalFieldsAndImmutableAnnotation_givenImmutableAnnotationIsIgnored_butItsADifferentImmutableAnnotation() { EqualsVerifier - .forClass(ImmutableByAnnotation.class) - .withIgnoredAnnotations(net.jcip.annotations.Immutable.class) - .verify(); + .forClass(ImmutableByAnnotation.class) + .withIgnoredAnnotations(net.jcip.annotations.Immutable.class) + .verify(); } @Test public void fail_whenIgnoredAnnotationClassIsntAnAnnotation() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(ImmutableByAnnotation.class) - .withIgnoredAnnotations(String.class) - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains("class", "java.lang.String", "is not an annotation"); + .when(() -> EqualsVerifier.forClass(ImmutableByAnnotation.class).withIgnoredAnnotations(String.class)) + .assertThrows(IllegalStateException.class) + .assertMessageContains("class", "java.lang.String", "is not an annotation"); } @Immutable diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/CachedHashCodeTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/CachedHashCodeTest.java index 17dfb83e7..8ad09ce75 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/CachedHashCodeTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/CachedHashCodeTest.java @@ -1,6 +1,7 @@ package nl.jqno.equalsverifier.integration.extra_features; import javax.annotation.Nonnull; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; @@ -11,346 +12,289 @@ public class CachedHashCodeTest { private static final String SOME_NAME = "some name"; private static final String CACHED_HASHCODE = "Cached hashCode:"; private static final String MALFORMED_CALCULATEHASHCODEMETHOD = - "Could not find calculateHashCodeMethod: must be 'private int"; + "Could not find calculateHashCodeMethod: must be 'private int"; private static final String MALFORMED_CACHEDHASHCODEFIELD = - "Could not find cachedHashCodeField: must be 'private int"; + "Could not find cachedHashCodeField: must be 'private int"; @Test public void fail_whenCachedHashCodeIsValid_givenWithCachedHashCodeIsNotUsed() { ExpectedException - .when(() -> EqualsVerifier.forClass(ObjectWithValidCachedHashCode.class).verify()) - .assertFailure() - .assertMessageContains( - "Significant fields", - "equals relies on", - "name", - "but hashCode does not" - ); + .when(() -> EqualsVerifier.forClass(ObjectWithValidCachedHashCode.class).verify()) + .assertFailure() + .assertMessageContains("Significant fields", "equals relies on", "name", "but hashCode does not"); } @Test public void succeed_whenCachedHashCodeIsValid_givenWithCachedHashCodeIsUsed() { EqualsVerifier - .forClass(ObjectWithValidCachedHashCode.class) - .withCachedHashCode( - "cachedHashCode", - "calcHashCode", - new ObjectWithValidCachedHashCode(SOME_NAME) - ) - .verify(); + .forClass(ObjectWithValidCachedHashCode.class) + .withCachedHashCode("cachedHashCode", "calcHashCode", new ObjectWithValidCachedHashCode(SOME_NAME)) + .verify(); } @Test public void succeed_whenCachedHashCodeIsValidAndLocatedInSuperclass_givenWithCachedHashCodeIsUsed() { EqualsVerifier - .forClass(Subclass.class) - .withCachedHashCode("cachedHashCode", "calcHashCode", new Subclass(SOME_NAME)) - .verify(); + .forClass(Subclass.class) + .withCachedHashCode("cachedHashCode", "calcHashCode", new Subclass(SOME_NAME)) + .verify(); } @Test public void fail_whenCachedHashCodeIsInvalid_givenWithCachedHashCodeIsUsed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(ObjectWithInvalidCachedHashCode.class) - .withCachedHashCode( - "cachedHashCode", - "calcHashCode", - new ObjectWithInvalidCachedHashCode(SOME_NAME) - ) - .verify() - ) - .assertFailure() - .assertMessageContains( - "Significant fields", - "equals relies on", - "name", - "but hashCode does not" - ); + .when( + () -> EqualsVerifier + .forClass(ObjectWithInvalidCachedHashCode.class) + .withCachedHashCode( + "cachedHashCode", + "calcHashCode", + new ObjectWithInvalidCachedHashCode(SOME_NAME)) + .verify()) + .assertFailure() + .assertMessageContains("Significant fields", "equals relies on", "name", "but hashCode does not"); } @Test public void fail_whenCachedHashCodeFieldDoesNotExist() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(ObjectWithValidCachedHashCode.class) - .withCachedHashCode( - "doesNotExist", - "calcHashCode", - new ObjectWithValidCachedHashCode(SOME_NAME) - ) - ) - .assertThrows(IllegalArgumentException.class) - .assertMessageContains(CACHED_HASHCODE, MALFORMED_CACHEDHASHCODEFIELD, "doesNotExist"); + .when( + () -> EqualsVerifier + .forClass(ObjectWithValidCachedHashCode.class) + .withCachedHashCode( + "doesNotExist", + "calcHashCode", + new ObjectWithValidCachedHashCode(SOME_NAME))) + .assertThrows(IllegalArgumentException.class) + .assertMessageContains(CACHED_HASHCODE, MALFORMED_CACHEDHASHCODEFIELD, "doesNotExist"); } @Test public void fail_whenCachedHashCodeFieldIsPublic() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(InvalidCachedHashCodeFieldContainer.class) - .withCachedHashCode( - "publicField", - "calculateHashCode", - new InvalidCachedHashCodeFieldContainer() - ) - ) - .assertThrows(IllegalArgumentException.class) - .assertMessageContains(CACHED_HASHCODE, MALFORMED_CACHEDHASHCODEFIELD, "publicField"); + .when( + () -> EqualsVerifier + .forClass(InvalidCachedHashCodeFieldContainer.class) + .withCachedHashCode( + "publicField", + "calculateHashCode", + new InvalidCachedHashCodeFieldContainer())) + .assertThrows(IllegalArgumentException.class) + .assertMessageContains(CACHED_HASHCODE, MALFORMED_CACHEDHASHCODEFIELD, "publicField"); } @Test public void fail_whenCachedHashCodeFieldIsNotAnInt() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(InvalidCachedHashCodeFieldContainer.class) - .withCachedHashCode( - "notAnInt", - "calculateHashCode", - new InvalidCachedHashCodeFieldContainer() - ) - ) - .assertThrows(IllegalArgumentException.class) - .assertMessageContains(CACHED_HASHCODE, MALFORMED_CACHEDHASHCODEFIELD, "notAnInt"); + .when( + () -> EqualsVerifier + .forClass(InvalidCachedHashCodeFieldContainer.class) + .withCachedHashCode( + "notAnInt", + "calculateHashCode", + new InvalidCachedHashCodeFieldContainer())) + .assertThrows(IllegalArgumentException.class) + .assertMessageContains(CACHED_HASHCODE, MALFORMED_CACHEDHASHCODEFIELD, "notAnInt"); } @Test public void fail_whenCalculateHashCodeMethodDoesNotExist() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(ObjectWithValidCachedHashCode.class) - .withCachedHashCode( - "cachedHashCode", - "doesNotExist", - new ObjectWithValidCachedHashCode(SOME_NAME) - ) - ) - .assertThrows(IllegalArgumentException.class) - .assertMessageContains( - CACHED_HASHCODE, - MALFORMED_CALCULATEHASHCODEMETHOD, - "doesNotExist" - ); + .when( + () -> EqualsVerifier + .forClass(ObjectWithValidCachedHashCode.class) + .withCachedHashCode( + "cachedHashCode", + "doesNotExist", + new ObjectWithValidCachedHashCode(SOME_NAME))) + .assertThrows(IllegalArgumentException.class) + .assertMessageContains(CACHED_HASHCODE, MALFORMED_CALCULATEHASHCODEMETHOD, "doesNotExist"); } @Test public void fail_whenCalculateHashCodeMethodDoesNotReturnInt() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(InvalidCalculateHashCodeMethodsContainer.class) - .withCachedHashCode( - "cachedHashCode", - "notAnInt", - new InvalidCalculateHashCodeMethodsContainer() - ) - ) - .assertThrows(IllegalArgumentException.class) - .assertMessageContains(CACHED_HASHCODE, MALFORMED_CALCULATEHASHCODEMETHOD, "notAnInt"); + .when( + () -> EqualsVerifier + .forClass(InvalidCalculateHashCodeMethodsContainer.class) + .withCachedHashCode( + "cachedHashCode", + "notAnInt", + new InvalidCalculateHashCodeMethodsContainer())) + .assertThrows(IllegalArgumentException.class) + .assertMessageContains(CACHED_HASHCODE, MALFORMED_CALCULATEHASHCODEMETHOD, "notAnInt"); } @Test public void fail_whenCalculateHashCodeMethodTakesParamters() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(InvalidCalculateHashCodeMethodsContainer.class) - .withCachedHashCode( - "cachedHashCode", - "takesParameters", - new InvalidCalculateHashCodeMethodsContainer() - ) - ) - .assertThrows(IllegalArgumentException.class) - .assertMessageContains( - CACHED_HASHCODE, - MALFORMED_CALCULATEHASHCODEMETHOD, - "takesParameters" - ); + .when( + () -> EqualsVerifier + .forClass(InvalidCalculateHashCodeMethodsContainer.class) + .withCachedHashCode( + "cachedHashCode", + "takesParameters", + new InvalidCalculateHashCodeMethodsContainer())) + .assertThrows(IllegalArgumentException.class) + .assertMessageContains(CACHED_HASHCODE, MALFORMED_CALCULATEHASHCODEMETHOD, "takesParameters"); } @Test public void fail_whenCalculateHashCodeMethodIsPublic() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(InvalidCalculateHashCodeMethodsContainer.class) - .withCachedHashCode( - "cachedHashCode", - "visible", - new InvalidCalculateHashCodeMethodsContainer() - ) - ) - .assertThrows(IllegalArgumentException.class) - .assertMessageContains(CACHED_HASHCODE, MALFORMED_CALCULATEHASHCODEMETHOD, "visible"); + .when( + () -> EqualsVerifier + .forClass(InvalidCalculateHashCodeMethodsContainer.class) + .withCachedHashCode( + "cachedHashCode", + "visible", + new InvalidCalculateHashCodeMethodsContainer())) + .assertThrows(IllegalArgumentException.class) + .assertMessageContains(CACHED_HASHCODE, MALFORMED_CALCULATEHASHCODEMETHOD, "visible"); } @Test public void succeed_whenCalculateHashCodeMethodAndCalcHashCodeFieldAreProtected() { EqualsVerifier - .forClass(ObjectWithProtectedCalculateHashCodeMembers.class) - .withCachedHashCode( - "cachedHashCode", - "calcHashCode", - new ObjectWithProtectedCalculateHashCodeMembers(SOME_NAME) - ) - .verify(); + .forClass(ObjectWithProtectedCalculateHashCodeMembers.class) + .withCachedHashCode( + "cachedHashCode", + "calcHashCode", + new ObjectWithProtectedCalculateHashCodeMembers(SOME_NAME)) + .verify(); } @Test public void succeed_whenCalculateHashCodeMethodAndCalcHashCodeFieldHaveDefaultVisibility() { EqualsVerifier - .forClass(ObjectWithDefaultVisibilityCalculateHashCodeMembers.class) - .withCachedHashCode( - "cachedHashCode", - "calcHashCode", - new ObjectWithDefaultVisibilityCalculateHashCodeMembers(SOME_NAME) - ) - .verify(); + .forClass(ObjectWithDefaultVisibilityCalculateHashCodeMembers.class) + .withCachedHashCode( + "cachedHashCode", + "calcHashCode", + new ObjectWithDefaultVisibilityCalculateHashCodeMembers(SOME_NAME)) + .verify(); } @Test public void fail_whenExampleIsNull() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(ObjectWithUninitializedCachedHashCode.class) - .withCachedHashCode("cachedHashCode", "calcHashCode", null) - .verify() - ) - .assertFailure() - .assertMessageContains(CACHED_HASHCODE, "example cannot be null."); + .when( + () -> EqualsVerifier + .forClass(ObjectWithUninitializedCachedHashCode.class) + .withCachedHashCode("cachedHashCode", "calcHashCode", null) + .verify()) + .assertFailure() + .assertMessageContains(CACHED_HASHCODE, "example cannot be null."); } @Test public void fail_whenCachedHashCodeFieldIsNotInitialized() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(ObjectWithUninitializedCachedHashCode.class) - .withCachedHashCode( - "cachedHashCode", - "calcHashCode", - new ObjectWithUninitializedCachedHashCode(SOME_NAME) - ) - .verify() - ) - .assertFailure() - .assertMessageContains(CACHED_HASHCODE, "hashCode is not properly initialized."); + .when( + () -> EqualsVerifier + .forClass(ObjectWithUninitializedCachedHashCode.class) + .withCachedHashCode( + "cachedHashCode", + "calcHashCode", + new ObjectWithUninitializedCachedHashCode(SOME_NAME)) + .verify()) + .assertFailure() + .assertMessageContains(CACHED_HASHCODE, "hashCode is not properly initialized."); } @Test public void fail_whenHashCodeIsZero() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(ObjectWithLegitimatelyZeroHashCode.class) - .withCachedHashCode( - "cachedHashCode", - "calcHashCode", - new ObjectWithLegitimatelyZeroHashCode(1) - ) - .verify() - ) - .assertFailure() - .assertMessageContains( - CACHED_HASHCODE, - "example.hashCode() cannot be zero. Please choose a different example." - ); + .when( + () -> EqualsVerifier + .forClass(ObjectWithLegitimatelyZeroHashCode.class) + .withCachedHashCode( + "cachedHashCode", + "calcHashCode", + new ObjectWithLegitimatelyZeroHashCode(1)) + .verify()) + .assertFailure() + .assertMessageContains( + CACHED_HASHCODE, + "example.hashCode() cannot be zero. Please choose a different example."); } @Test public void succeed_whenCachedHashCodeFieldIsNotInitialized_givenExampleIsNullAndNoExampleForCachedHashCodeIsSuppressed() { EqualsVerifier - .forClass(ObjectWithUninitializedCachedHashCode.class) - .withCachedHashCode("cachedHashCode", "calcHashCode", null) - .suppress(Warning.NO_EXAMPLE_FOR_CACHED_HASHCODE) - .verify(); + .forClass(ObjectWithUninitializedCachedHashCode.class) + .withCachedHashCode("cachedHashCode", "calcHashCode", null) + .suppress(Warning.NO_EXAMPLE_FOR_CACHED_HASHCODE) + .verify(); } @Test public void fail_whenNoExampleForCachedHashCodeIsSuppressedAndExampleIsNotNull() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(ObjectWithValidCachedHashCode.class) - .withCachedHashCode( - "cachedHashCode", - "calcHashCode", - new ObjectWithValidCachedHashCode(SOME_NAME) - ) - .suppress(Warning.NO_EXAMPLE_FOR_CACHED_HASHCODE) - .verify() - ) - .assertFailure() - .assertMessageContains( - CACHED_HASHCODE, - "example must be null if " + - Warning.NO_EXAMPLE_FOR_CACHED_HASHCODE + - " is suppressed" - ); + .when( + () -> EqualsVerifier + .forClass(ObjectWithValidCachedHashCode.class) + .withCachedHashCode( + "cachedHashCode", + "calcHashCode", + new ObjectWithValidCachedHashCode(SOME_NAME)) + .suppress(Warning.NO_EXAMPLE_FOR_CACHED_HASHCODE) + .verify()) + .assertFailure() + .assertMessageContains( + CACHED_HASHCODE, + "example must be null if " + Warning.NO_EXAMPLE_FOR_CACHED_HASHCODE + " is suppressed"); } @Test public void fail_whenCachedHashCodeIsValid_givenWithCachedHashCodeIsUsedAndWarningNonfinalFieldsIsSuppressed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(ObjectWithValidCachedHashCode.class) - .withCachedHashCode( - "cachedHashCode", - "calcHashCode", - new ObjectWithValidCachedHashCode(SOME_NAME) - ) - .suppress(Warning.NONFINAL_FIELDS) - .verify() - ) - .assertFailure() - .assertMessageContains( - CACHED_HASHCODE, - "EqualsVerifier can only check cached hashCodes for immutable classes." - ); + .when( + () -> EqualsVerifier + .forClass(ObjectWithValidCachedHashCode.class) + .withCachedHashCode( + "cachedHashCode", + "calcHashCode", + new ObjectWithValidCachedHashCode(SOME_NAME)) + .suppress(Warning.NONFINAL_FIELDS) + .verify()) + .assertFailure() + .assertMessageContains( + CACHED_HASHCODE, + "EqualsVerifier can only check cached hashCodes for immutable classes."); } @Test public void succeed_whenCachedHashCodeIsLazilyInitialized_givenItIsValid() { EqualsVerifier - .forClass(ObjectWithLazilyInitializedCachedHashCode.class) - .withCachedHashCode( - "cachedHashCode", - "calcHashCode", - new ObjectWithLazilyInitializedCachedHashCode(SOME_NAME) - ) - .verify(); + .forClass(ObjectWithLazilyInitializedCachedHashCode.class) + .withCachedHashCode( + "cachedHashCode", + "calcHashCode", + new ObjectWithLazilyInitializedCachedHashCode(SOME_NAME)) + .verify(); } @Test public void succeed_whenCachedHashCodeIsLazilyInitializedAndCachedHashCodeFieldIsCalledInEquals_givenItIsValid() { EqualsVerifier - .forClass(ObjectWithLazyCachedHashCodeAndFieldIsCalledInEquals.class) - .withCachedHashCode( - "cachedHashCode", - "calcHashCode", - new ObjectWithLazyCachedHashCodeAndFieldIsCalledInEquals(SOME_NAME) - ) - .verify(); + .forClass(ObjectWithLazyCachedHashCodeAndFieldIsCalledInEquals.class) + .withCachedHashCode( + "cachedHashCode", + "calcHashCode", + new ObjectWithLazyCachedHashCodeAndFieldIsCalledInEquals(SOME_NAME)) + .verify(); } @Test public void succeed_whenCachedHashCodeIsLazilyInitializedAndHashCodeMethodIsCalledInEquals_givenItIsValid() { EqualsVerifier - .forClass(ObjectWithLazyCachedHashCodeAndMethodIsCalledInEquals.class) - .withCachedHashCode( - "cachedHashCode", - "calcHashCode", - new ObjectWithLazyCachedHashCodeAndMethodIsCalledInEquals(SOME_NAME) - ) - .verify(); + .forClass(ObjectWithLazyCachedHashCodeAndMethodIsCalledInEquals.class) + .withCachedHashCode( + "cachedHashCode", + "calcHashCode", + new ObjectWithLazyCachedHashCodeAndMethodIsCalledInEquals(SOME_NAME)) + .verify(); } static class ObjectWithValidCachedHashCode { @@ -468,8 +412,7 @@ public final boolean equals(Object obj) { if (!(obj instanceof ObjectWithProtectedCalculateHashCodeMembers)) { return false; } - ObjectWithProtectedCalculateHashCodeMembers that = - (ObjectWithProtectedCalculateHashCodeMembers) obj; + ObjectWithProtectedCalculateHashCodeMembers that = (ObjectWithProtectedCalculateHashCodeMembers) obj; return name.equals(that.name); } @@ -501,7 +444,7 @@ public final boolean equals(Object obj) { return false; } ObjectWithDefaultVisibilityCalculateHashCodeMembers that = - (ObjectWithDefaultVisibilityCalculateHashCodeMembers) obj; + (ObjectWithDefaultVisibilityCalculateHashCodeMembers) obj; return name.equals(that.name); } @@ -532,8 +475,7 @@ public final boolean equals(Object obj) { if (!(obj instanceof ObjectWithUninitializedCachedHashCode)) { return false; } - ObjectWithUninitializedCachedHashCode that = - (ObjectWithUninitializedCachedHashCode) obj; + ObjectWithUninitializedCachedHashCode that = (ObjectWithUninitializedCachedHashCode) obj; return name.equals(that.name); } @@ -595,8 +537,7 @@ public final boolean equals(Object obj) { if (!(obj instanceof ObjectWithLazilyInitializedCachedHashCode)) { return false; } - ObjectWithLazilyInitializedCachedHashCode that = - (ObjectWithLazilyInitializedCachedHashCode) obj; + ObjectWithLazilyInitializedCachedHashCode that = (ObjectWithLazilyInitializedCachedHashCode) obj; return name.equals(that.name); } @@ -630,7 +571,7 @@ public final boolean equals(Object obj) { return false; } ObjectWithLazyCachedHashCodeAndFieldIsCalledInEquals that = - (ObjectWithLazyCachedHashCodeAndFieldIsCalledInEquals) obj; + (ObjectWithLazyCachedHashCodeAndFieldIsCalledInEquals) obj; if (cachedHashCode != that.cachedHashCode) { return false; } @@ -670,7 +611,7 @@ public final boolean equals(Object obj) { return false; } ObjectWithLazyCachedHashCodeAndMethodIsCalledInEquals that = - (ObjectWithLazyCachedHashCodeAndMethodIsCalledInEquals) obj; + (ObjectWithLazyCachedHashCodeAndMethodIsCalledInEquals) obj; return name.equals(that.name); } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/GetClassTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/GetClassTest.java index e9c57449c..fbfd75fb0 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/GetClassTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/GetClassTest.java @@ -16,13 +16,12 @@ public class GetClassTest { @Test public void fail_whenEqualsUsesGetClassInsteadOfInstanceof() { ExpectedException - .when(() -> EqualsVerifier.forClass(GetClassPoint.class).verify()) - .assertFailure() - .assertMessageContains( - "Subclass", - "object is not equal to an instance of a trivial subclass with equal fields", - "Maybe you forgot to add usingGetClass()" - ); + .when(() -> EqualsVerifier.forClass(GetClassPoint.class).verify()) + .assertFailure() + .assertMessageContains( + "Subclass", + "object is not equal to an instance of a trivial subclass with equal fields", + "Maybe you forgot to add usingGetClass()"); } @Test @@ -38,30 +37,29 @@ public void succeed_whenEqualsUsesGetClassInsteadOfInstanceof_givenWarningStrict @Test public void fail_whenEqualsUsesGetClassButForgetsToCheckNull_givenUsingGetClassIsUsed() { ExpectedException - .when(() -> EqualsVerifier.forClass(GetClassPointNull.class).usingGetClass().verify()) - .assertFailure() - .assertCause(NullPointerException.class) - .assertMessageContains("Non-nullity: NullPointerException thrown"); + .when(() -> EqualsVerifier.forClass(GetClassPointNull.class).usingGetClass().verify()) + .assertFailure() + .assertCause(NullPointerException.class) + .assertMessageContains("Non-nullity: NullPointerException thrown"); } @Test public void fail_whenEqualsUsesInstanceof_givenUsingGetClassIsUsed() { ExpectedException - .when(() -> EqualsVerifier.forClass(FinalMethodsPoint.class).usingGetClass().verify()) - .assertFailure() - .assertMessageContains( - "Subclass", - "object is equal to an instance of a trivial subclass with equal fields", - "This should not happen when using getClass()." - ); + .when(() -> EqualsVerifier.forClass(FinalMethodsPoint.class).usingGetClass().verify()) + .assertFailure() + .assertMessageContains( + "Subclass", + "object is equal to an instance of a trivial subclass with equal fields", + "This should not happen when using getClass()."); } @Test public void fail_whenSuperclassUsesGetClass() { ExpectedException - .when(() -> EqualsVerifier.forClass(GetClassColorPoint.class).verify()) - .assertFailure() - .assertMessageContains("Symmetry", "does not equal superclass instance"); + .when(() -> EqualsVerifier.forClass(GetClassColorPoint.class).verify()) + .assertFailure() + .assertMessageContains("Symmetry", "does not equal superclass instance"); } @Test @@ -71,29 +69,20 @@ public void succeed_whenSuperclassUsesGetClass_givenUsingGetClassIsUsed() { @Test public void succeed_whenSuperclassUsesGetClass_givenWarningStrictInheritanceIsSuppressed() { - EqualsVerifier - .forClass(GetClassColorPoint.class) - .suppress(Warning.STRICT_INHERITANCE) - .verify(); + EqualsVerifier.forClass(GetClassColorPoint.class).suppress(Warning.STRICT_INHERITANCE).verify(); } @Test public void fail_whenEqualsUsesGetClassButSuperclassUsesInstanceof_givenUsingGetClassIsUsed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(GetClassColorPointWithEqualSuper.class) - .usingGetClass() - .verify() - ) - .assertFailure() - .assertMessageContains( - "Redefined superclass", - GetClassColorPointWithEqualSuper.class.getSimpleName(), - "should not equal superclass instance", - Point.class.getSimpleName(), - "but it does" - ); + .when(() -> EqualsVerifier.forClass(GetClassColorPointWithEqualSuper.class).usingGetClass().verify()) + .assertFailure() + .assertMessageContains( + "Redefined superclass", + GetClassColorPointWithEqualSuper.class.getSimpleName(), + "should not equal superclass instance", + Point.class.getSimpleName(), + "but it does"); } static class GetClassPointNull { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/JakartaEntityTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/JakartaEntityTest.java index a905f0cdc..214cb8b3b 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/JakartaEntityTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/JakartaEntityTest.java @@ -3,6 +3,7 @@ import static nl.jqno.equalsverifier.internal.testhelpers.Util.defaultHashCode; import java.util.Objects; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; import org.junit.jupiter.api.Test; @@ -17,9 +18,9 @@ public void succeed_whenClassIsNonFinalAndFieldsAreMutable_givenClassHasJpaEntit @Test public void fail_whenClassIsNonFinalAndFieldsAreMutable_givenSuperclassHasJpaEntityAnnotationButThisClassDoesnt() { ExpectedException - .when(() -> EqualsVerifier.forClass(SubclassEntityByJakartaAnnotation.class).verify()) - .assertFailure() - .assertMessageContains("Subclass"); + .when(() -> EqualsVerifier.forClass(SubclassEntityByJakartaAnnotation.class).verify()) + .assertFailure() + .assertMessageContains("Subclass"); } @Test @@ -30,11 +31,9 @@ public void succeed_whenFieldsAreMutable_givenClassHasJpaEmbeddableAnnotation() @Test public void fail_whenFieldsAreMutable_givenSuperclassHasJpaEmbeddableAnnotationButThisClassDoesnt() { ExpectedException - .when(() -> - EqualsVerifier.forClass(SubclassEmbeddableByJakartaAnnotation.class).verify() - ) - .assertFailure() - .assertMessageContains("Subclass"); + .when(() -> EqualsVerifier.forClass(SubclassEmbeddableByJakartaAnnotation.class).verify()) + .assertFailure() + .assertMessageContains("Subclass"); } @Test @@ -45,11 +44,9 @@ public void succeed_whenFieldsAreMutable_givenClassHasJpaMappedSuperclassAnnotat @Test public void fail_whenFieldsAreMutable_givenSuperclassHasJpaMappedSuperclassAnnotationButThisClassDoesnt() { ExpectedException - .when(() -> - EqualsVerifier.forClass(SubclassMappedSuperclassByJakartaAnnotation.class).verify() - ) - .assertFailure() - .assertMessageContains("Subclass"); + .when(() -> EqualsVerifier.forClass(SubclassMappedSuperclassByJakartaAnnotation.class).verify()) + .assertFailure() + .assertMessageContains("Subclass"); } @jakarta.persistence.Entity @@ -143,6 +140,5 @@ public int hashCode() { } } - static class SubclassMappedSuperclassByJakartaAnnotation - extends MappedSuperclassByJakartaAnnotation {} + static class SubclassMappedSuperclassByJakartaAnnotation extends MappedSuperclassByJakartaAnnotation {} } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/JakartaIdTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/JakartaIdTest.java index d6992e48f..60df9780b 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/JakartaIdTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/JakartaIdTest.java @@ -3,6 +3,7 @@ import java.time.LocalDate; import java.util.Objects; import java.util.UUID; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; @@ -20,158 +21,135 @@ public void succeed_whenIdFieldIsNotUsed_givenIdIsAnnotatedWithId() { @Test public void succeed_whenOnlyIdFieldIsUsed_givenIdIsAnnotatedWithIdAndSurrogateKeyWarningIsSuppressed() { + EqualsVerifier.forClass(JakartaIdSurrogateKeyPerson.class).suppress(Warning.SURROGATE_KEY).verify(); EqualsVerifier - .forClass(JakartaIdSurrogateKeyPerson.class) - .suppress(Warning.SURROGATE_KEY) - .verify(); - EqualsVerifier - .forClass(JakartaIdSurrogateKeyPersonReorderedFields.class) - .suppress(Warning.SURROGATE_KEY) - .verify(); + .forClass(JakartaIdSurrogateKeyPersonReorderedFields.class) + .suppress(Warning.SURROGATE_KEY) + .verify(); } @Test public void succeed_whenAllFieldsAreUsed_givenIdIsAnnotatedWithIdAndJpaKeyWarningIsSuppressed() { + EqualsVerifier.forClass(JakartaIdValueKeyPerson.class).suppress(Warning.SURROGATE_OR_BUSINESS_KEY).verify(); EqualsVerifier - .forClass(JakartaIdValueKeyPerson.class) - .suppress(Warning.SURROGATE_OR_BUSINESS_KEY) - .verify(); - EqualsVerifier - .forClass(JakartaIdValueKeyPersonReorderedFields.class) - .suppress(Warning.SURROGATE_OR_BUSINESS_KEY) - .verify(); + .forClass(JakartaIdValueKeyPersonReorderedFields.class) + .suppress(Warning.SURROGATE_OR_BUSINESS_KEY) + .verify(); } @Test public void fail_whenIdFieldIsNotUsed_givenIdIsAnnotatedWithIdButIdAnnotationIsIgnored() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(JakartaIdBusinessKeyPerson.class) - .withIgnoredAnnotations(jakarta.persistence.Id.class) - .verify() - ) - .assertFailure() - .assertMessageContains("Significant fields", "equals does not use id"); + .when( + () -> EqualsVerifier + .forClass(JakartaIdBusinessKeyPerson.class) + .withIgnoredAnnotations(jakarta.persistence.Id.class) + .verify()) + .assertFailure() + .assertMessageContains("Significant fields", "equals does not use id"); } @Test public void fail_whenOnlyIdFieldIsUsed_givenIdIsAnnotatedWithId() { ExpectedException - .when(() -> EqualsVerifier.forClass(JakartaIdSurrogateKeyPerson.class).verify()) - .assertFailure() - .assertMessageContains( - "Significant fields", - "id is marked @Id", - "equals should not use it", - "Suppress Warning.SURROGATE_KEY" - ); + .when(() -> EqualsVerifier.forClass(JakartaIdSurrogateKeyPerson.class).verify()) + .assertFailure() + .assertMessageContains( + "Significant fields", + "id is marked @Id", + "equals should not use it", + "Suppress Warning.SURROGATE_KEY"); } @Test public void fail_whenOnlyIdFieldIsUsed_givenIdIsAnnotatedWithId2() { ExpectedException - .when(() -> - EqualsVerifier.forClass(JakartaIdSurrogateKeyPersonReorderedFields.class).verify() - ) - .assertFailure() - .assertMessageContains( - "Significant fields", - "equals does not use socialSecurity", - "Suppress Warning.SURROGATE_KEY" - ); + .when(() -> EqualsVerifier.forClass(JakartaIdSurrogateKeyPersonReorderedFields.class).verify()) + .assertFailure() + .assertMessageContains( + "Significant fields", + "equals does not use socialSecurity", + "Suppress Warning.SURROGATE_KEY"); } @Test public void fail_whenIdFieldIsNotUsed_givenIdIsAnnotatedWithIdAndSurrogateKeyWarningIsSuppressed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(JakartaIdBusinessKeyPerson.class) - .suppress(Warning.SURROGATE_KEY) - .verify() - ) - .assertFailure() - .assertMessageContains( - "Significant fields", - "id is marked @Id", - "Warning.SURROGATE_KEY", - "equals does not use" - ); + .when( + () -> EqualsVerifier + .forClass(JakartaIdBusinessKeyPerson.class) + .suppress(Warning.SURROGATE_KEY) + .verify()) + .assertFailure() + .assertMessageContains( + "Significant fields", + "id is marked @Id", + "Warning.SURROGATE_KEY", + "equals does not use"); } @Test public void fail_whenIdFieldIsNotUsed_givenIdIsAnnotatedWithIdAndSurrogateKeyWarningIsSuppressed2() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(JakartaIdBusinessKeyPersonReorderedFields.class) - .suppress(Warning.SURROGATE_KEY) - .verify() - ) - .assertFailure() - .assertMessageContains( - "Significant fields", - "equals should not use socialSecurity", - "Warning.SURROGATE_KEY is suppressed and it is not marked as @Id", - "but it does" - ); + .when( + () -> EqualsVerifier + .forClass(JakartaIdBusinessKeyPersonReorderedFields.class) + .suppress(Warning.SURROGATE_KEY) + .verify()) + .assertFailure() + .assertMessageContains( + "Significant fields", + "equals should not use socialSecurity", + "Warning.SURROGATE_KEY is suppressed and it is not marked as @Id", + "but it does"); } @Test public void succeed_whenEmbeddedIdIsUsedCorrectly() { EqualsVerifier.forClass(JakartaEmbeddedIdBusinessKeyPerson.class).verify(); - EqualsVerifier - .forClass(JakartaEmbeddedIdSurrogateKeyPerson.class) - .suppress(Warning.SURROGATE_KEY) - .verify(); + EqualsVerifier.forClass(JakartaEmbeddedIdSurrogateKeyPerson.class).suppress(Warning.SURROGATE_KEY).verify(); } @Test public void fail_whenOnlyEmbeddedIdFieldIsUsed_givenIdIsAnnotatedWithEmbeddedId() { ExpectedException - .when(() -> EqualsVerifier.forClass(JakartaEmbeddedIdSurrogateKeyPerson.class).verify()) - .assertFailure() - .assertMessageContains( - "Significant fields", - "id is marked @Id or @EmbeddedId", - "equals should not use it", - "Suppress Warning.SURROGATE_KEY" - ); + .when(() -> EqualsVerifier.forClass(JakartaEmbeddedIdSurrogateKeyPerson.class).verify()) + .assertFailure() + .assertMessageContains( + "Significant fields", + "id is marked @Id or @EmbeddedId", + "equals should not use it", + "Suppress Warning.SURROGATE_KEY"); } @Test public void fail_whenIdFieldIsNotUsed_givenIdIsAnnotatedWithEmbeddedIdAndSurrogateKeyWarningIsSuppressed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(JakartaEmbeddedIdBusinessKeyPerson.class) - .suppress(Warning.SURROGATE_KEY) - .verify() - ) - .assertFailure() - .assertMessageContains( - "Significant fields", - "id is marked @Id or @EmbeddedId", - "Warning.SURROGATE_KEY", - "equals does not use" - ); + .when( + () -> EqualsVerifier + .forClass(JakartaEmbeddedIdBusinessKeyPerson.class) + .suppress(Warning.SURROGATE_KEY) + .verify()) + .assertFailure() + .assertMessageContains( + "Significant fields", + "id is marked @Id or @EmbeddedId", + "Warning.SURROGATE_KEY", + "equals does not use"); } @Test public void fail_whenEmbeddedIdFieldIsTheOnlyFieldUsed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(JakartaEmbeddedIdBusinessKeyPerson.class) - .withOnlyTheseFields("id") - .verify() - ) - .assertFailure() - .assertMessageContains( - "Precondition: you can't use withOnlyTheseFields on a field marked @Id or @EmbeddedId.", - "Suppress Warning.SURROGATE_KEY" - ); + .when( + () -> EqualsVerifier + .forClass(JakartaEmbeddedIdBusinessKeyPerson.class) + .withOnlyTheseFields("id") + .verify()) + .assertFailure() + .assertMessageContains( + "Precondition: you can't use withOnlyTheseFields on a field marked @Id or @EmbeddedId.", + "Suppress Warning.SURROGATE_KEY"); } @Test @@ -182,30 +160,26 @@ public void succeed_whenOnlySocialSecurityIsUsed_givenSocialSecurityIsAnnotatedW @Test public void fail_whenOnlySocialSecurityIsUsed_givenSocialSecurityIsAnnotatedWithNaturalIdButIdAnnotationIsIgnored() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(NaturalIdBusinessKeyPerson.class) - .withIgnoredAnnotations(NaturalId.class) - .verify() - ) - .assertFailure() - .assertMessageContains("Significant fields", "equals does not use name"); + .when( + () -> EqualsVerifier + .forClass(NaturalIdBusinessKeyPerson.class) + .withIgnoredAnnotations(NaturalId.class) + .verify()) + .assertFailure() + .assertMessageContains("Significant fields", "equals does not use name"); } @Test public void succeed_whenIdAndNameFieldsAreNotUsed_givenNameIsIgnored() { - EqualsVerifier - .forClass(JakartaIdBusinessKeyPersonDoesntUseName.class) - .withIgnoredFields("name") - .verify(); + EqualsVerifier.forClass(JakartaIdBusinessKeyPersonDoesntUseName.class).withIgnoredFields("name").verify(); } @Test public void succeed_whenIdAndNameFieldsAreNotUsed_givenSocialSecurityAndBirthdateAreOnlyUsed() { EqualsVerifier - .forClass(JakartaIdBusinessKeyPersonDoesntUseName.class) - .withOnlyTheseFields("socialSecurity", "birthdate") - .verify(); + .forClass(JakartaIdBusinessKeyPersonDoesntUseName.class) + .withOnlyTheseFields("socialSecurity", "birthdate") + .verify(); } @Test @@ -221,9 +195,9 @@ public void succeed_whenNaturalIdIsPartOfAProperJakartaEntity() { @Test public void succeed_whenEqualsBehavesLikeVersionedEntity_givenIdIsMarkedWithIdAndWarningVersionedEntityIsSuppressed() { EqualsVerifier - .forClass(JakartaIdVersionedEntity.class) - .suppress(Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY, Warning.SURROGATE_KEY) - .verify(); + .forClass(JakartaIdVersionedEntity.class) + .suppress(Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY, Warning.SURROGATE_KEY) + .verify(); } @Test @@ -234,164 +208,139 @@ public void succeed_whenMethodsAreAnnotatedInsteadOfFields() { @Test public void fail_whenIdFieldIsTheOnlyFieldUsed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(JakartaIdBusinessKeyPerson.class) - .withOnlyTheseFields("id") - .verify() - ) - .assertFailure() - .assertMessageContains( - "Precondition: you can't use withOnlyTheseFields on a field marked @Id or @EmbeddedId.", - "Suppress Warning.SURROGATE_KEY" - ); + .when( + () -> EqualsVerifier.forClass(JakartaIdBusinessKeyPerson.class).withOnlyTheseFields("id").verify()) + .assertFailure() + .assertMessageContains( + "Precondition: you can't use withOnlyTheseFields on a field marked @Id or @EmbeddedId.", + "Suppress Warning.SURROGATE_KEY"); } @Test public void fail_whenOnlySocialSecurityIsUsed_givenSocialSecurityIsAnnotatedWithNaturalIdButSurrogateKeyWarningIsSuppressed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(NaturalIdBusinessKeyPerson.class) - .suppress(Warning.SURROGATE_KEY) - .verify() - ) - .assertFailure() - .assertMessageContains( - "Precondition: you can't suppress Warning.SURROGATE_KEY when fields are marked @NaturalId." - ); + .when( + () -> EqualsVerifier + .forClass(NaturalIdBusinessKeyPerson.class) + .suppress(Warning.SURROGATE_KEY) + .verify()) + .assertFailure() + .assertMessageContains( + "Precondition: you can't suppress Warning.SURROGATE_KEY when fields are marked @NaturalId."); } @Test public void fail_whenWithOnlyTheseFieldsIsUsed_givenWarningSurrogateKeyIsSuppressed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(JakartaIdSurrogateKeyPerson.class) - .withOnlyTheseFields("socialSecurity") - .suppress(Warning.SURROGATE_KEY) - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "Precondition", - "you can't use withOnlyTheseFields when Warning.SURROGATE_KEY is suppressed." - ); + .when( + () -> EqualsVerifier + .forClass(JakartaIdSurrogateKeyPerson.class) + .withOnlyTheseFields("socialSecurity") + .suppress(Warning.SURROGATE_KEY)) + .assertThrows(IllegalStateException.class) + .assertMessageContains( + "Precondition", + "you can't use withOnlyTheseFields when Warning.SURROGATE_KEY is suppressed."); } @Test public void fail_whenWithOnlyTheseFieldsIsUsed_givenWarningSurrogateKeyIsSuppressedInReverse() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(JakartaIdSurrogateKeyPerson.class) - .suppress(Warning.SURROGATE_KEY) - .withOnlyTheseFields("socialSecurity") - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "Precondition", - "you can't use withOnlyTheseFields when Warning.SURROGATE_KEY is suppressed." - ); + .when( + () -> EqualsVerifier + .forClass(JakartaIdSurrogateKeyPerson.class) + .suppress(Warning.SURROGATE_KEY) + .withOnlyTheseFields("socialSecurity")) + .assertThrows(IllegalStateException.class) + .assertMessageContains( + "Precondition", + "you can't use withOnlyTheseFields when Warning.SURROGATE_KEY is suppressed."); } @Test public void fail_whenFieldsAreIgnored_givenWarningSurrogateKeyIsSuppressed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(JakartaIdSurrogateKeyPerson.class) - .withIgnoredFields("socialSecurity") - .suppress(Warning.SURROGATE_KEY) - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "Precondition: you can't use withIgnoredFields when Warning.SURROGATE_KEY is suppressed." - ); + .when( + () -> EqualsVerifier + .forClass(JakartaIdSurrogateKeyPerson.class) + .withIgnoredFields("socialSecurity") + .suppress(Warning.SURROGATE_KEY)) + .assertThrows(IllegalStateException.class) + .assertMessageContains( + "Precondition: you can't use withIgnoredFields when Warning.SURROGATE_KEY is suppressed."); } @Test public void fail_whenFieldsAreIgnored_givenWarningSurrogateKeyIsSuppressedInReverse() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(JakartaIdSurrogateKeyPerson.class) - .suppress(Warning.SURROGATE_KEY) - .withIgnoredFields("socialSecurity") - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "Precondition: you can't use withIgnoredFields when Warning.SURROGATE_KEY is suppressed." - ); + .when( + () -> EqualsVerifier + .forClass(JakartaIdSurrogateKeyPerson.class) + .suppress(Warning.SURROGATE_KEY) + .withIgnoredFields("socialSecurity")) + .assertThrows(IllegalStateException.class) + .assertMessageContains( + "Precondition: you can't use withIgnoredFields when Warning.SURROGATE_KEY is suppressed."); } @Test public void fail_whenWithOnlyTheseFieldsIsUsed_givenFieldsAreMarkedWithNaturalId() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(NaturalIdBusinessKeyPerson.class) - .withOnlyTheseFields("socialSecurity") - .verify() - ) - .assertFailure() - .assertMessageContains( - "Precondition: you can't use withOnlyTheseFields when fields are marked with @NaturalId." - ); + .when( + () -> EqualsVerifier + .forClass(NaturalIdBusinessKeyPerson.class) + .withOnlyTheseFields("socialSecurity") + .verify()) + .assertFailure() + .assertMessageContains( + "Precondition: you can't use withOnlyTheseFields when fields are marked with @NaturalId."); } @Test public void fail_whenFieldsAreIgnored_givenFieldsAreMarkedWithNaturalId() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(NaturalIdBusinessKeyPerson.class) - .withIgnoredFields("socialSecurity") - .verify() - ) - .assertFailure() - .assertMessageContains( - "Precondition: you can't use withIgnoredFields when fields are marked with @NaturalId." - ); + .when( + () -> EqualsVerifier + .forClass(NaturalIdBusinessKeyPerson.class) + .withIgnoredFields("socialSecurity") + .verify()) + .assertFailure() + .assertMessageContains( + "Precondition: you can't use withIgnoredFields when fields are marked with @NaturalId."); } @Test public void fail_whenWarningVersionedEntityIsSuppressed_givenAFieldIsAnnotatedWithNaturalId() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(NaturalIdBusinessKeyPerson.class) - .suppress(Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY) - .verify() - ) - .assertFailure() - .assertMessageContains( - "Precondition: you can't suppress Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY when fields are marked with @NaturalId." - ); + .when( + () -> EqualsVerifier + .forClass(NaturalIdBusinessKeyPerson.class) + .suppress(Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY) + .verify()) + .assertFailure() + .assertMessageContains( + "Precondition: you can't suppress Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY when fields are marked with @NaturalId."); } @Test public void fail_whenWarningSurrogateKeyIsSuppressed_givenWarningSurrogateOrBusinessKeyIsAlsoSuppressed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(JakartaIdBusinessKeyPerson.class) - .suppress(Warning.SURROGATE_KEY, Warning.SURROGATE_OR_BUSINESS_KEY) - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "Precondition", - "you can't suppress Warning.SURROGATE_KEY when Warning.SURROGATE_OR_BUSINESS_KEY is also suppressed." - ); + .when( + () -> EqualsVerifier + .forClass(JakartaIdBusinessKeyPerson.class) + .suppress(Warning.SURROGATE_KEY, Warning.SURROGATE_OR_BUSINESS_KEY)) + .assertThrows(IllegalStateException.class) + .assertMessageContains( + "Precondition", + "you can't suppress Warning.SURROGATE_KEY when Warning.SURROGATE_OR_BUSINESS_KEY is also suppressed."); } @Test public void fail_whenANaturalIdAnnotationFromAnotherPackageIsUsed() { ExpectedException - .when(() -> - EqualsVerifier.forClass(NonHibernateNaturalIdBusinessKeyPerson.class).verify() - ) - .assertFailure() - .assertMessageContains("Significant fields"); + .when(() -> EqualsVerifier.forClass(NonHibernateNaturalIdBusinessKeyPerson.class).verify()) + .assertFailure() + .assertMessageContains("Significant fields"); } @Test @@ -402,10 +351,10 @@ public void succeed_whenEqualsIsImplementedInSuperclass_givenWarningSurrogateKey @Test public void succeed_whenEqualsUsesIdsAndNonIds_givenWarningSurrogateOrBusinessKeyIsSuppressed() { EqualsVerifier - .forClass(JakartaIdDirtyTrackingPerson.class) - .suppress(Warning.SURROGATE_OR_BUSINESS_KEY) - .withOnlyTheseFields("id", "version", "isDirty") - .verify(); + .forClass(JakartaIdDirtyTrackingPerson.class) + .suppress(Warning.SURROGATE_OR_BUSINESS_KEY) + .withOnlyTheseFields("id", "version", "isDirty") + .verify(); } static class JakartaIdBusinessKeyPerson { @@ -417,12 +366,7 @@ static class JakartaIdBusinessKeyPerson { private final String name; private final LocalDate birthdate; - public JakartaIdBusinessKeyPerson( - UUID id, - String socialSecurity, - String name, - LocalDate birthdate - ) { + public JakartaIdBusinessKeyPerson(UUID id, String socialSecurity, String name, LocalDate birthdate) { this.id = id; this.socialSecurity = socialSecurity; this.name = name; @@ -435,11 +379,9 @@ public final boolean equals(Object obj) { return false; } JakartaIdBusinessKeyPerson other = (JakartaIdBusinessKeyPerson) obj; - return ( - Objects.equals(socialSecurity, other.socialSecurity) && - Objects.equals(name, other.name) && - Objects.equals(birthdate, other.birthdate) - ); + return Objects.equals(socialSecurity, other.socialSecurity) + && Objects.equals(name, other.name) + && Objects.equals(birthdate, other.birthdate); } @Override @@ -458,11 +400,10 @@ static class JakartaIdBusinessKeyPersonReorderedFields { private final UUID id; public JakartaIdBusinessKeyPersonReorderedFields( - UUID id, - String socialSecurity, - String name, - LocalDate birthdate - ) { + UUID id, + String socialSecurity, + String name, + LocalDate birthdate) { this.id = id; this.socialSecurity = socialSecurity; this.name = name; @@ -474,13 +415,10 @@ public final boolean equals(Object obj) { if (!(obj instanceof JakartaIdBusinessKeyPersonReorderedFields)) { return false; } - JakartaIdBusinessKeyPersonReorderedFields other = - (JakartaIdBusinessKeyPersonReorderedFields) obj; - return ( - Objects.equals(socialSecurity, other.socialSecurity) && - Objects.equals(name, other.name) && - Objects.equals(birthdate, other.birthdate) - ); + JakartaIdBusinessKeyPersonReorderedFields other = (JakartaIdBusinessKeyPersonReorderedFields) obj; + return Objects.equals(socialSecurity, other.socialSecurity) + && Objects.equals(name, other.name) + && Objects.equals(birthdate, other.birthdate); } @Override @@ -498,12 +436,7 @@ static class JakartaIdSurrogateKeyPerson { private final String name; private final LocalDate birthdate; - public JakartaIdSurrogateKeyPerson( - UUID id, - String socialSecurity, - String name, - LocalDate birthdate - ) { + public JakartaIdSurrogateKeyPerson(UUID id, String socialSecurity, String name, LocalDate birthdate) { this.id = id; this.socialSecurity = socialSecurity; this.name = name; @@ -535,11 +468,10 @@ static class JakartaIdSurrogateKeyPersonReorderedFields { private final UUID id; public JakartaIdSurrogateKeyPersonReorderedFields( - UUID id, - String socialSecurity, - String name, - LocalDate birthdate - ) { + UUID id, + String socialSecurity, + String name, + LocalDate birthdate) { this.id = id; this.socialSecurity = socialSecurity; this.name = name; @@ -551,8 +483,7 @@ public final boolean equals(Object obj) { if (!(obj instanceof JakartaIdSurrogateKeyPersonReorderedFields)) { return false; } - JakartaIdSurrogateKeyPersonReorderedFields other = - (JakartaIdSurrogateKeyPersonReorderedFields) obj; + JakartaIdSurrogateKeyPersonReorderedFields other = (JakartaIdSurrogateKeyPersonReorderedFields) obj; return Objects.equals(id, other.id); } @@ -571,12 +502,7 @@ static class JakartaIdValueKeyPerson { private final String name; private final LocalDate birthdate; - public JakartaIdValueKeyPerson( - UUID id, - String socialSecurity, - String name, - LocalDate birthdate - ) { + public JakartaIdValueKeyPerson(UUID id, String socialSecurity, String name, LocalDate birthdate) { this.id = id; this.socialSecurity = socialSecurity; this.name = name; @@ -589,12 +515,10 @@ public final boolean equals(Object obj) { return false; } JakartaIdValueKeyPerson other = (JakartaIdValueKeyPerson) obj; - return ( - Objects.equals(id, other.id) && - Objects.equals(socialSecurity, other.socialSecurity) && - Objects.equals(name, other.name) && - Objects.equals(birthdate, other.birthdate) - ); + return Objects.equals(id, other.id) + && Objects.equals(socialSecurity, other.socialSecurity) + && Objects.equals(name, other.name) + && Objects.equals(birthdate, other.birthdate); } @Override @@ -613,11 +537,10 @@ static class JakartaIdValueKeyPersonReorderedFields { private final UUID id; public JakartaIdValueKeyPersonReorderedFields( - UUID id, - String socialSecurity, - String name, - LocalDate birthdate - ) { + UUID id, + String socialSecurity, + String name, + LocalDate birthdate) { this.id = id; this.socialSecurity = socialSecurity; this.name = name; @@ -629,14 +552,11 @@ public final boolean equals(Object obj) { if (!(obj instanceof JakartaIdValueKeyPersonReorderedFields)) { return false; } - JakartaIdValueKeyPersonReorderedFields other = - (JakartaIdValueKeyPersonReorderedFields) obj; - return ( - Objects.equals(socialSecurity, other.socialSecurity) && - Objects.equals(name, other.name) && - Objects.equals(birthdate, other.birthdate) && - Objects.equals(id, other.id) - ); + JakartaIdValueKeyPersonReorderedFields other = (JakartaIdValueKeyPersonReorderedFields) obj; + return Objects.equals(socialSecurity, other.socialSecurity) + && Objects.equals(name, other.name) + && Objects.equals(birthdate, other.birthdate) + && Objects.equals(id, other.id); } @Override @@ -654,12 +574,7 @@ static class JakartaEmbeddedIdBusinessKeyPerson { private final String name; private final LocalDate birthdate; - public JakartaEmbeddedIdBusinessKeyPerson( - UUID id, - String socialSecurity, - String name, - LocalDate birthdate - ) { + public JakartaEmbeddedIdBusinessKeyPerson(UUID id, String socialSecurity, String name, LocalDate birthdate) { this.id = id; this.socialSecurity = socialSecurity; this.name = name; @@ -672,11 +587,9 @@ public final boolean equals(Object obj) { return false; } JakartaEmbeddedIdBusinessKeyPerson other = (JakartaEmbeddedIdBusinessKeyPerson) obj; - return ( - Objects.equals(socialSecurity, other.socialSecurity) && - Objects.equals(name, other.name) && - Objects.equals(birthdate, other.birthdate) - ); + return Objects.equals(socialSecurity, other.socialSecurity) + && Objects.equals(name, other.name) + && Objects.equals(birthdate, other.birthdate); } @Override @@ -694,12 +607,7 @@ static class JakartaEmbeddedIdSurrogateKeyPerson { private final String name; private final LocalDate birthdate; - public JakartaEmbeddedIdSurrogateKeyPerson( - UUID id, - String socialSecurity, - String name, - LocalDate birthdate - ) { + public JakartaEmbeddedIdSurrogateKeyPerson(UUID id, String socialSecurity, String name, LocalDate birthdate) { this.id = id; this.socialSecurity = socialSecurity; this.name = name; @@ -732,12 +640,7 @@ static class NaturalIdBusinessKeyPerson { private final String name; private final LocalDate birthdate; - public NaturalIdBusinessKeyPerson( - UUID id, - String socialSecurity, - String name, - LocalDate birthdate - ) { + public NaturalIdBusinessKeyPerson(UUID id, String socialSecurity, String name, LocalDate birthdate) { this.id = id; this.socialSecurity = socialSecurity; this.name = name; @@ -769,11 +672,10 @@ static class JakartaIdBusinessKeyPersonDoesntUseName { private final LocalDate birthdate; public JakartaIdBusinessKeyPersonDoesntUseName( - UUID id, - String socialSecurity, - String name, - LocalDate birthdate - ) { + UUID id, + String socialSecurity, + String name, + LocalDate birthdate) { this.id = id; this.socialSecurity = socialSecurity; this.name = name; @@ -785,12 +687,8 @@ public final boolean equals(Object obj) { if (!(obj instanceof JakartaIdBusinessKeyPersonDoesntUseName)) { return false; } - JakartaIdBusinessKeyPersonDoesntUseName other = - (JakartaIdBusinessKeyPersonDoesntUseName) obj; - return ( - Objects.equals(socialSecurity, other.socialSecurity) && - Objects.equals(birthdate, other.birthdate) - ); + JakartaIdBusinessKeyPersonDoesntUseName other = (JakartaIdBusinessKeyPersonDoesntUseName) obj; + return Objects.equals(socialSecurity, other.socialSecurity) && Objects.equals(birthdate, other.birthdate); } @Override @@ -815,11 +713,9 @@ public final boolean equals(Object obj) { return false; } JakartaIdBusinessKeyPersonEntity other = (JakartaIdBusinessKeyPersonEntity) obj; - return ( - Objects.equals(socialSecurity, other.socialSecurity) && - Objects.equals(name, other.name) && - Objects.equals(birthdate, other.birthdate) - ); + return Objects.equals(socialSecurity, other.socialSecurity) + && Objects.equals(name, other.name) + && Objects.equals(birthdate, other.birthdate); } @Override @@ -867,11 +763,10 @@ static class NonHibernateNaturalIdBusinessKeyPerson { private final LocalDate birthdate; public NonHibernateNaturalIdBusinessKeyPerson( - UUID id, - String socialSecurity, - String name, - LocalDate birthdate - ) { + UUID id, + String socialSecurity, + String name, + LocalDate birthdate) { this.id = id; this.socialSecurity = socialSecurity; this.name = name; @@ -883,8 +778,7 @@ public final boolean equals(Object obj) { if (!(obj instanceof NonHibernateNaturalIdBusinessKeyPerson)) { return false; } - NonHibernateNaturalIdBusinessKeyPerson other = - (NonHibernateNaturalIdBusinessKeyPerson) obj; + NonHibernateNaturalIdBusinessKeyPerson other = (NonHibernateNaturalIdBusinessKeyPerson) obj; return Objects.equals(socialSecurity, other.socialSecurity); } @@ -931,12 +825,7 @@ static class MethodAnnotatedBusinessKeyPerson { private final String name; private final LocalDate birthdate; - public MethodAnnotatedBusinessKeyPerson( - UUID id, - String socialSecurity, - String name, - LocalDate birthdate - ) { + public MethodAnnotatedBusinessKeyPerson(UUID id, String socialSecurity, String name, LocalDate birthdate) { this.id = id; this.socialSecurity = socialSecurity; this.name = name; @@ -1029,11 +918,9 @@ public final boolean equals(Object obj) { return false; } JakartaIdDirtyTrackingPerson other = (JakartaIdDirtyTrackingPerson) obj; - return ( - Objects.equals(id, other.id) && - Objects.equals(version, other.version) && - Objects.equals(isDirty, other.isDirty) - ); + return Objects.equals(id, other.id) + && Objects.equals(version, other.version) + && Objects.equals(isDirty, other.isDirty); } @Override diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/JakartaLazyEntityTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/JakartaLazyEntityTest.java index a9f29ce92..8c6e18d92 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/JakartaLazyEntityTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/JakartaLazyEntityTest.java @@ -1,8 +1,9 @@ package nl.jqno.equalsverifier.integration.extra_features; -import jakarta.persistence.*; import java.util.Arrays; import java.util.Objects; + +import jakarta.persistence.*; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; @@ -14,35 +15,32 @@ public class JakartaLazyEntityTest { @Test public void gettersAreUsed() { - EqualsVerifier - .forClass(CorrectJakartaLazyFieldContainer.class) - .suppress(Warning.NONFINAL_FIELDS) - .verify(); + EqualsVerifier.forClass(CorrectJakartaLazyFieldContainer.class).suppress(Warning.NONFINAL_FIELDS).verify(); } @Test public void basicGetterNotUsed_givenEagerLoading() { EqualsVerifier - .forClass(CorrectBasicJakartaEagerFieldContainer.class) - .suppress(Warning.NONFINAL_FIELDS) - .verify(); + .forClass(CorrectBasicJakartaEagerFieldContainer.class) + .suppress(Warning.NONFINAL_FIELDS) + .verify(); } @Test public void basicGetterNotUsed_givenCorrespondingFieldIgnored() { EqualsVerifier - .forClass(CorrectBasicJakartaIgnoredLazyFieldContainer.class) - .withIgnoredFields("basic") - .suppress(Warning.NONFINAL_FIELDS) - .verify(); + .forClass(CorrectBasicJakartaIgnoredLazyFieldContainer.class) + .withIgnoredFields("basic") + .suppress(Warning.NONFINAL_FIELDS) + .verify(); } @Test public void basicGetterNotUsed_givenWarningSuppressed() { EqualsVerifier - .forClass(CorrectBasicJakartaIgnoredLazyFieldContainer.class) - .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) - .verify(); + .forClass(CorrectBasicJakartaIgnoredLazyFieldContainer.class) + .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) + .verify(); } @Test @@ -101,74 +99,52 @@ public void lazyGettersPickedUpInSuper() { @Test public void constantHashCode_givenStrictHashCodeSuppressed() { - EqualsVerifier - .forClass(ConstantHashCodeContainer.class) - .suppress(Warning.STRICT_HASHCODE) - .verify(); + EqualsVerifier.forClass(ConstantHashCodeContainer.class).suppress(Warning.STRICT_HASHCODE).verify(); } @Test public void differentCodingStyle_single() { EqualsVerifier - .forClass(DifferentCodingStyleContainer.class) - .suppress(Warning.NONFINAL_FIELDS) - .withFieldnameToGetterConverter(fn -> - "get" + Character.toUpperCase(fn.charAt(2)) + fn.substring(3) - ) - .verify(); + .forClass(DifferentCodingStyleContainer.class) + .suppress(Warning.NONFINAL_FIELDS) + .withFieldnameToGetterConverter(fn -> "get" + Character.toUpperCase(fn.charAt(2)) + fn.substring(3)) + .verify(); } @Test public void differentCodingStyle_configured() { EqualsVerifier - .configure() - .suppress(Warning.NONFINAL_FIELDS) - .withFieldnameToGetterConverter(fn -> - "get" + Character.toUpperCase(fn.charAt(2)) + fn.substring(3) - ) - .forClass(DifferentCodingStyleContainer.class) - .verify(); + .configure() + .suppress(Warning.NONFINAL_FIELDS) + .withFieldnameToGetterConverter(fn -> "get" + Character.toUpperCase(fn.charAt(2)) + fn.substring(3)) + .forClass(DifferentCodingStyleContainer.class) + .verify(); } @Test public void differentCodingStyle_multiple() { EqualsVerifier - .forClasses(Arrays.asList(DifferentCodingStyleContainer.class)) - .suppress(Warning.NONFINAL_FIELDS) - .withFieldnameToGetterConverter(fn -> - "get" + Character.toUpperCase(fn.charAt(2)) + fn.substring(3) - ) - .verify(); + .forClasses(Arrays.asList(DifferentCodingStyleContainer.class)) + .suppress(Warning.NONFINAL_FIELDS) + .withFieldnameToGetterConverter(fn -> "get" + Character.toUpperCase(fn.charAt(2)) + fn.substring(3)) + .verify(); } @Test public void getterUsedForGeneratedId() { + EqualsVerifier.forClass(CorrectGeneratedJakartaIdContainer.class).suppress(Warning.SURROGATE_KEY).verify(); EqualsVerifier - .forClass(CorrectGeneratedJakartaIdContainer.class) - .suppress(Warning.SURROGATE_KEY) - .verify(); - EqualsVerifier - .forClass(CorrectGeneratedJakartaIdContainer.class) - .suppress(Warning.SURROGATE_OR_BUSINESS_KEY) - .verify(); + .forClass(CorrectGeneratedJakartaIdContainer.class) + .suppress(Warning.SURROGATE_OR_BUSINESS_KEY) + .verify(); } @Test public void getterNotUsedForGeneratedId() { getterNotUsed(IncorrectGeneratedJakartaIdContainer.class, "equals", Warning.SURROGATE_KEY); - getterNotUsed_warningSuppressed( - IncorrectGeneratedJakartaIdContainer.class, - Warning.SURROGATE_KEY - ); - getterNotUsed( - IncorrectGeneratedJakartaIdContainer.class, - "equals", - Warning.SURROGATE_OR_BUSINESS_KEY - ); - getterNotUsed_warningSuppressed( - IncorrectGeneratedJakartaIdContainer.class, - Warning.SURROGATE_OR_BUSINESS_KEY - ); + getterNotUsed_warningSuppressed(IncorrectGeneratedJakartaIdContainer.class, Warning.SURROGATE_KEY); + getterNotUsed(IncorrectGeneratedJakartaIdContainer.class, "equals", Warning.SURROGATE_OR_BUSINESS_KEY); + getterNotUsed_warningSuppressed(IncorrectGeneratedJakartaIdContainer.class, Warning.SURROGATE_OR_BUSINESS_KEY); } @Test @@ -183,17 +159,13 @@ public void finalEntitiesArentLazy() { private void getterNotUsed(Class type, String method, Warning... additionalWarnings) { ExpectedException - .when(() -> EqualsVerifier.forClass(type).suppress(additionalWarnings).verify()) - .assertFailure() - .assertMessageContains("JPA Entity", method, "direct reference"); + .when(() -> EqualsVerifier.forClass(type).suppress(additionalWarnings).verify()) + .assertFailure() + .assertMessageContains("JPA Entity", method, "direct reference"); } private void getterNotUsed_warningSuppressed(Class type, Warning... additionalWarnings) { - EqualsVerifier - .forClass(type) - .suppress(Warning.JPA_GETTER) - .suppress(additionalWarnings) - .verify(); + EqualsVerifier.forClass(type).suppress(Warning.JPA_GETTER).suppress(additionalWarnings).verify(); } @Entity @@ -247,26 +219,24 @@ public boolean equals(Object obj) { return false; } CorrectJakartaLazyFieldContainer other = (CorrectJakartaLazyFieldContainer) obj; - return ( - Objects.equals(getBasic(), other.getBasic()) && - Objects.equals(getOneToOne(), other.getOneToOne()) && - Objects.equals(getOneToMany(), other.getOneToMany()) && - Objects.equals(getManyToOne(), other.getManyToOne()) && - Objects.equals(getManyToMany(), other.getManyToMany()) && - Objects.equals(getElementCollection(), other.getElementCollection()) - ); + return Objects.equals(getBasic(), other.getBasic()) + && Objects.equals(getOneToOne(), other.getOneToOne()) + && Objects.equals(getOneToMany(), other.getOneToMany()) + && Objects.equals(getManyToOne(), other.getManyToOne()) + && Objects.equals(getManyToMany(), other.getManyToMany()) + && Objects.equals(getElementCollection(), other.getElementCollection()); } @Override public int hashCode() { - return Objects.hash( - getBasic(), - getOneToOne(), - getOneToMany(), - getManyToOne(), - getManyToMany(), - getElementCollection() - ); + return Objects + .hash( + getBasic(), + getOneToOne(), + getOneToMany(), + getManyToOne(), + getManyToMany(), + getElementCollection()); } } @@ -285,8 +255,7 @@ public boolean equals(Object obj) { if (!(obj instanceof CorrectBasicJakartaEagerFieldContainer)) { return false; } - CorrectBasicJakartaEagerFieldContainer other = - (CorrectBasicJakartaEagerFieldContainer) obj; + CorrectBasicJakartaEagerFieldContainer other = (CorrectBasicJakartaEagerFieldContainer) obj; return Objects.equals(basic, other.basic); } @@ -313,8 +282,7 @@ public boolean equals(Object obj) { if (!(obj instanceof CorrectBasicJakartaIgnoredLazyFieldContainer)) { return false; } - CorrectBasicJakartaIgnoredLazyFieldContainer other = - (CorrectBasicJakartaIgnoredLazyFieldContainer) obj; + CorrectBasicJakartaIgnoredLazyFieldContainer other = (CorrectBasicJakartaIgnoredLazyFieldContainer) obj; return Objects.equals(somethingElse, other.somethingElse); } @@ -339,8 +307,7 @@ public boolean equals(Object obj) { if (!(obj instanceof IncorrectBasicJakartaLazyGetterContainer)) { return false; } - IncorrectBasicJakartaLazyGetterContainer other = - (IncorrectBasicJakartaLazyGetterContainer) obj; + IncorrectBasicJakartaLazyGetterContainer other = (IncorrectBasicJakartaLazyGetterContainer) obj; return Objects.equals(basic, other.basic); } @@ -366,7 +333,7 @@ public boolean equals(Object obj) { return false; } IncorrectBasicJakartaLazyFieldContainerHashCode other = - (IncorrectBasicJakartaLazyFieldContainerHashCode) obj; + (IncorrectBasicJakartaLazyFieldContainerHashCode) obj; return Objects.equals(getBasic(), other.getBasic()); } @@ -391,8 +358,7 @@ public boolean equals(Object obj) { if (!(obj instanceof IncorrectBasicJakartaLazyFieldContainer)) { return false; } - IncorrectBasicJakartaLazyFieldContainer other = - (IncorrectBasicJakartaLazyFieldContainer) obj; + IncorrectBasicJakartaLazyFieldContainer other = (IncorrectBasicJakartaLazyFieldContainer) obj; return Objects.equals(basic, other.basic); } @@ -417,8 +383,7 @@ public boolean equals(Object obj) { if (!(obj instanceof IncorrectOneToOneJakartaLazyFieldContainer)) { return false; } - IncorrectOneToOneJakartaLazyFieldContainer other = - (IncorrectOneToOneJakartaLazyFieldContainer) obj; + IncorrectOneToOneJakartaLazyFieldContainer other = (IncorrectOneToOneJakartaLazyFieldContainer) obj; return Objects.equals(oneToOne, other.oneToOne); } @@ -443,8 +408,7 @@ public boolean equals(Object obj) { if (!(obj instanceof IncorrectOneToManyJakartaLazyFieldContainer)) { return false; } - IncorrectOneToManyJakartaLazyFieldContainer other = - (IncorrectOneToManyJakartaLazyFieldContainer) obj; + IncorrectOneToManyJakartaLazyFieldContainer other = (IncorrectOneToManyJakartaLazyFieldContainer) obj; return Objects.equals(oneToMany, other.oneToMany); } @@ -469,8 +433,7 @@ public boolean equals(Object obj) { if (!(obj instanceof IncorrectManyToOneJakartaLazyFieldContainer)) { return false; } - IncorrectManyToOneJakartaLazyFieldContainer other = - (IncorrectManyToOneJakartaLazyFieldContainer) obj; + IncorrectManyToOneJakartaLazyFieldContainer other = (IncorrectManyToOneJakartaLazyFieldContainer) obj; return Objects.equals(manyToOne, other.manyToOne); } @@ -495,8 +458,7 @@ public boolean equals(Object obj) { if (!(obj instanceof IncorrectManyToManyJakartaLazyFieldContainer)) { return false; } - IncorrectManyToManyJakartaLazyFieldContainer other = - (IncorrectManyToManyJakartaLazyFieldContainer) obj; + IncorrectManyToManyJakartaLazyFieldContainer other = (IncorrectManyToManyJakartaLazyFieldContainer) obj; return Objects.equals(manyToMany, other.manyToMany); } @@ -522,7 +484,7 @@ public boolean equals(Object obj) { return false; } IncorrectElementCollectionJakartaLazyFieldContainer other = - (IncorrectElementCollectionJakartaLazyFieldContainer) obj; + (IncorrectElementCollectionJakartaLazyFieldContainer) obj; return Objects.equals(elementCollection, other.elementCollection); } @@ -597,10 +559,8 @@ public boolean equals(Object obj) { return false; } ConstantHashCodeContainer other = (ConstantHashCodeContainer) obj; - return ( - Objects.equals(getOneToMany(), other.getOneToMany()) && - Objects.equals(getManyToOne(), other.getManyToOne()) - ); + return Objects.equals(getOneToMany(), other.getOneToMany()) + && Objects.equals(getManyToOne(), other.getManyToOne()); } @Override @@ -635,10 +595,8 @@ public boolean equals(Object obj) { return false; } DifferentCodingStyleContainer other = (DifferentCodingStyleContainer) obj; - return ( - Objects.equals(getOneToMany(), other.getOneToMany()) && - Objects.equals(getManyToOne(), other.getManyToOne()) - ); + return Objects.equals(getOneToMany(), other.getOneToMany()) + && Objects.equals(getManyToOne(), other.getManyToOne()); } @Override diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/JpaEntityTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/JpaEntityTest.java index 8eb023b18..2848f44c2 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/JpaEntityTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/JpaEntityTest.java @@ -3,6 +3,7 @@ import static nl.jqno.equalsverifier.internal.testhelpers.Util.defaultHashCode; import java.util.Objects; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; import org.junit.jupiter.api.Test; @@ -17,17 +18,17 @@ public void succeed_whenClassIsNonFinalAndFieldsAreMutable_givenClassHasJpaEntit @Test public void fail_whenClassIsNonFinalAndFieldsAreMutable_givenSuperclassHasJpaEntityAnnotationButThisClassDoesnt() { ExpectedException - .when(() -> EqualsVerifier.forClass(SubclassEntityByJpaAnnotation.class).verify()) - .assertFailure() - .assertMessageContains("Subclass"); + .when(() -> EqualsVerifier.forClass(SubclassEntityByJpaAnnotation.class).verify()) + .assertFailure() + .assertMessageContains("Subclass"); } @Test public void fail_whenClassIsJpaEntity_givenEntityAnnotationResidesInWrongPackage() { ExpectedException - .when(() -> EqualsVerifier.forClass(EntityByNonJpaAnnotation.class).verify()) - .assertFailure() - .assertMessageContains("Subclass"); + .when(() -> EqualsVerifier.forClass(EntityByNonJpaAnnotation.class).verify()) + .assertFailure() + .assertMessageContains("Subclass"); } @Test @@ -38,17 +39,17 @@ public void succeed_whenFieldsAreMutable_givenClassHasJpaEmbeddableAnnotation() @Test public void fail_whenFieldsAreMutable_givenSuperclassHasJpaEmbeddableAnnotationButThisClassDoesnt() { ExpectedException - .when(() -> EqualsVerifier.forClass(SubclassEmbeddableByJpaAnnotation.class).verify()) - .assertFailure() - .assertMessageContains("Subclass"); + .when(() -> EqualsVerifier.forClass(SubclassEmbeddableByJpaAnnotation.class).verify()) + .assertFailure() + .assertMessageContains("Subclass"); } @Test public void fail_whenClassIsJpaEmbeddable_givenEmbeddableAnnotationResidesInWrongPackage() { ExpectedException - .when(() -> EqualsVerifier.forClass(EmbeddableByNonJpaAnnotation.class).verify()) - .assertFailure() - .assertMessageContains("Subclass"); + .when(() -> EqualsVerifier.forClass(EmbeddableByNonJpaAnnotation.class).verify()) + .assertFailure() + .assertMessageContains("Subclass"); } @Test @@ -59,19 +60,17 @@ public void succeed_whenFieldsAreMutable_givenClassHasJpaMappedSuperclassAnnotat @Test public void fail_whenFieldsAreMutable_givenSuperclassHasJpaMappedSuperclassAnnotationButThisClassDoesnt() { ExpectedException - .when(() -> - EqualsVerifier.forClass(SubclassMappedSuperclassByJpaAnnotation.class).verify() - ) - .assertFailure() - .assertMessageContains("Subclass"); + .when(() -> EqualsVerifier.forClass(SubclassMappedSuperclassByJpaAnnotation.class).verify()) + .assertFailure() + .assertMessageContains("Subclass"); } @Test public void fail_whenClassIsJpaMappedSuperclass_givenMappedSuperclassAnnotationResidesInWrongPackage() { ExpectedException - .when(() -> EqualsVerifier.forClass(MappedSuperclassByNonJpaAnnotation.class).verify()) - .assertFailure() - .assertMessageContains("Subclass"); + .when(() -> EqualsVerifier.forClass(MappedSuperclassByNonJpaAnnotation.class).verify()) + .assertFailure() + .assertMessageContains("Subclass"); } @nl.jqno.equalsverifier.testhelpers.annotations.javax.persistence.Entity diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/JpaIdTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/JpaIdTest.java index 46d68bfee..29112710d 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/JpaIdTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/JpaIdTest.java @@ -3,6 +3,7 @@ import java.time.LocalDate; import java.util.Objects; import java.util.UUID; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; @@ -23,158 +24,132 @@ public void succeed_whenIdFieldIsNotUsed_givenIdIsAnnotatedWithId() { @Test public void succeed_whenOnlyIdFieldIsUsed_givenIdIsAnnotatedWithIdAndSurrogateKeyWarningIsSuppressed() { - EqualsVerifier - .forClass(JpaIdSurrogateKeyPerson.class) - .suppress(Warning.SURROGATE_KEY) - .verify(); - EqualsVerifier - .forClass(JpaIdSurrogateKeyPersonReorderedFields.class) - .suppress(Warning.SURROGATE_KEY) - .verify(); + EqualsVerifier.forClass(JpaIdSurrogateKeyPerson.class).suppress(Warning.SURROGATE_KEY).verify(); + EqualsVerifier.forClass(JpaIdSurrogateKeyPersonReorderedFields.class).suppress(Warning.SURROGATE_KEY).verify(); } @Test public void succeed_whenAllFieldsAreUsed_givenIdIsAnnotatedWithIdAndJpaKeyWarningIsSuppressed() { + EqualsVerifier.forClass(JpaIdValueKeyPerson.class).suppress(Warning.SURROGATE_OR_BUSINESS_KEY).verify(); EqualsVerifier - .forClass(JpaIdValueKeyPerson.class) - .suppress(Warning.SURROGATE_OR_BUSINESS_KEY) - .verify(); - EqualsVerifier - .forClass(JpaIdValueKeyPersonReorderedFields.class) - .suppress(Warning.SURROGATE_OR_BUSINESS_KEY) - .verify(); + .forClass(JpaIdValueKeyPersonReorderedFields.class) + .suppress(Warning.SURROGATE_OR_BUSINESS_KEY) + .verify(); } @Test public void fail_whenIdFieldIsNotUsed_givenIdIsAnnotatedWithIdButIdAnnotationIsIgnored() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(JpaIdBusinessKeyPerson.class) - .withIgnoredAnnotations(Id.class) - .verify() - ) - .assertFailure() - .assertMessageContains("Significant fields", "equals does not use id"); + .when( + () -> EqualsVerifier + .forClass(JpaIdBusinessKeyPerson.class) + .withIgnoredAnnotations(Id.class) + .verify()) + .assertFailure() + .assertMessageContains("Significant fields", "equals does not use id"); } @Test public void fail_whenOnlyIdFieldIsUsed_givenIdIsAnnotatedWithId() { ExpectedException - .when(() -> EqualsVerifier.forClass(JpaIdSurrogateKeyPerson.class).verify()) - .assertFailure() - .assertMessageContains( - "Significant fields", - "id is marked @Id", - "equals should not use it", - "Suppress Warning.SURROGATE_KEY if" - ); + .when(() -> EqualsVerifier.forClass(JpaIdSurrogateKeyPerson.class).verify()) + .assertFailure() + .assertMessageContains( + "Significant fields", + "id is marked @Id", + "equals should not use it", + "Suppress Warning.SURROGATE_KEY if"); } @Test public void fail_whenOnlyIdFieldIsUsed_givenIdIsAnnotatedWithId2() { ExpectedException - .when(() -> - EqualsVerifier.forClass(JpaIdSurrogateKeyPersonReorderedFields.class).verify() - ) - .assertFailure() - .assertMessageContains( - "Significant fields", - "equals does not use socialSecurity", - "Suppress Warning.SURROGATE_KEY if" - ); + .when(() -> EqualsVerifier.forClass(JpaIdSurrogateKeyPersonReorderedFields.class).verify()) + .assertFailure() + .assertMessageContains( + "Significant fields", + "equals does not use socialSecurity", + "Suppress Warning.SURROGATE_KEY if"); } @Test public void fail_whenIdFieldIsNotUsed_givenIdIsAnnotatedWithIdAndSurrogateKeyWarningIsSuppressed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(JpaIdBusinessKeyPerson.class) - .suppress(Warning.SURROGATE_KEY) - .verify() - ) - .assertFailure() - .assertMessageContains( - "Significant fields", - "id is marked @Id", - "Warning.SURROGATE_KEY", - "equals does not use" - ); + .when( + () -> EqualsVerifier + .forClass(JpaIdBusinessKeyPerson.class) + .suppress(Warning.SURROGATE_KEY) + .verify()) + .assertFailure() + .assertMessageContains( + "Significant fields", + "id is marked @Id", + "Warning.SURROGATE_KEY", + "equals does not use"); } @Test public void fail_whenIdFieldIsNotUsed_givenIdIsAnnotatedWithIdAndSurrogateKeyWarningIsSuppressed2() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(JpaIdBusinessKeyPersonReorderedFields.class) - .suppress(Warning.SURROGATE_KEY) - .verify() - ) - .assertFailure() - .assertMessageContains( - "Significant fields", - "equals should not use socialSecurity", - "Warning.SURROGATE_KEY is suppressed and it is not marked as @Id", - "but it does" - ); + .when( + () -> EqualsVerifier + .forClass(JpaIdBusinessKeyPersonReorderedFields.class) + .suppress(Warning.SURROGATE_KEY) + .verify()) + .assertFailure() + .assertMessageContains( + "Significant fields", + "equals should not use socialSecurity", + "Warning.SURROGATE_KEY is suppressed and it is not marked as @Id", + "but it does"); } @Test public void succeed_whenEmbeddedIdIsUsedCorrectly() { EqualsVerifier.forClass(JpaEmbeddedIdBusinessKeyPerson.class).verify(); - EqualsVerifier - .forClass(JpaEmbeddedIdSurrogateKeyPerson.class) - .suppress(Warning.SURROGATE_KEY) - .verify(); + EqualsVerifier.forClass(JpaEmbeddedIdSurrogateKeyPerson.class).suppress(Warning.SURROGATE_KEY).verify(); } @Test public void fail_whenOnlyEmbeddedIdFieldIsUsed_givenIdIsAnnotatedWithEmbeddedId() { ExpectedException - .when(() -> EqualsVerifier.forClass(JpaEmbeddedIdSurrogateKeyPerson.class).verify()) - .assertFailure() - .assertMessageContains( - "Significant fields", - "id is marked @Id or @EmbeddedId", - "equals should not use it", - "Suppress Warning.SURROGATE_KEY if" - ); + .when(() -> EqualsVerifier.forClass(JpaEmbeddedIdSurrogateKeyPerson.class).verify()) + .assertFailure() + .assertMessageContains( + "Significant fields", + "id is marked @Id or @EmbeddedId", + "equals should not use it", + "Suppress Warning.SURROGATE_KEY if"); } @Test public void fail_whenIdFieldIsNotUsed_givenIdIsAnnotatedWithEmbeddedIdAndSurrogateKeyWarningIsSuppressed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(JpaEmbeddedIdBusinessKeyPerson.class) - .suppress(Warning.SURROGATE_KEY) - .verify() - ) - .assertFailure() - .assertMessageContains( - "Significant fields", - "id is marked @Id or @EmbeddedId", - "Warning.SURROGATE_KEY", - "equals does not use" - ); + .when( + () -> EqualsVerifier + .forClass(JpaEmbeddedIdBusinessKeyPerson.class) + .suppress(Warning.SURROGATE_KEY) + .verify()) + .assertFailure() + .assertMessageContains( + "Significant fields", + "id is marked @Id or @EmbeddedId", + "Warning.SURROGATE_KEY", + "equals does not use"); } @Test public void fail_whenEmbeddedIdFieldIsTheOnlyFieldUsed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(JpaEmbeddedIdBusinessKeyPerson.class) - .withOnlyTheseFields("id") - .verify() - ) - .assertFailure() - .assertMessageContains( - "Precondition: you can't use withOnlyTheseFields on a field marked @Id or @EmbeddedId.", - "Suppress Warning.SURROGATE_KEY" - ); + .when( + () -> EqualsVerifier + .forClass(JpaEmbeddedIdBusinessKeyPerson.class) + .withOnlyTheseFields("id") + .verify()) + .assertFailure() + .assertMessageContains( + "Precondition: you can't use withOnlyTheseFields on a field marked @Id or @EmbeddedId.", + "Suppress Warning.SURROGATE_KEY"); } @Test @@ -190,30 +165,26 @@ public void succeed_whenOnlySocialSecurityIsUsed_givenSocialSecurityIsAnnotatedW @Test public void fail_whenOnlySocialSecurityIsUsed_givenSocialSecurityIsAnnotatedWithNaturalIdButIdAnnotationIsIgnored() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(NaturalIdBusinessKeyPerson.class) - .withIgnoredAnnotations(NaturalId.class) - .verify() - ) - .assertFailure() - .assertMessageContains("Significant fields", "equals does not use name"); + .when( + () -> EqualsVerifier + .forClass(NaturalIdBusinessKeyPerson.class) + .withIgnoredAnnotations(NaturalId.class) + .verify()) + .assertFailure() + .assertMessageContains("Significant fields", "equals does not use name"); } @Test public void succeed_whenIdAndNameFieldsAreNotUsed_givenNameIsIgnored() { - EqualsVerifier - .forClass(JpaIdBusinessKeyPersonDoesntUseName.class) - .withIgnoredFields("name") - .verify(); + EqualsVerifier.forClass(JpaIdBusinessKeyPersonDoesntUseName.class).withIgnoredFields("name").verify(); } @Test public void succeed_whenIdAndNameFieldsAreNotUsed_givenSocialSecurityAndBirthdateAreOnlyUsed() { EqualsVerifier - .forClass(JpaIdBusinessKeyPersonDoesntUseName.class) - .withOnlyTheseFields("socialSecurity", "birthdate") - .verify(); + .forClass(JpaIdBusinessKeyPersonDoesntUseName.class) + .withOnlyTheseFields("socialSecurity", "birthdate") + .verify(); } @Test @@ -229,9 +200,9 @@ public void succeed_whenNaturalIdIsPartOfAProperJpaEntity() { @Test public void succeed_whenEqualsBehavesLikeVersionedEntity_givenIdIsMarkedWithIdAndWarningVersionedEntityIsSuppressed() { EqualsVerifier - .forClass(JpaIdVersionedEntity.class) - .suppress(Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY, Warning.SURROGATE_KEY) - .verify(); + .forClass(JpaIdVersionedEntity.class) + .suppress(Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY, Warning.SURROGATE_KEY) + .verify(); } @Test @@ -242,172 +213,146 @@ public void succeed_whenMethodsAreAnnotatedInsteadOfFields() { @Test public void fail_whenIdFieldIsTheOnlyFieldUsed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(JpaIdBusinessKeyPerson.class) - .withOnlyTheseFields("id") - .verify() - ) - .assertFailure() - .assertMessageContains( - "Precondition: you can't use withOnlyTheseFields on a field marked @Id or @EmbeddedId.", - "Suppress Warning.SURROGATE_KEY" - ); + .when(() -> EqualsVerifier.forClass(JpaIdBusinessKeyPerson.class).withOnlyTheseFields("id").verify()) + .assertFailure() + .assertMessageContains( + "Precondition: you can't use withOnlyTheseFields on a field marked @Id or @EmbeddedId.", + "Suppress Warning.SURROGATE_KEY"); } @Test public void fail_whenOnlySocialSecurityIsUsed_givenSocialSecurityIsAnnotatedWithNaturalIdButSurrogateKeyWarningIsSuppressed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(NaturalIdBusinessKeyPerson.class) - .suppress(Warning.SURROGATE_KEY) - .verify() - ) - .assertFailure() - .assertMessageContains( - "Precondition: you can't suppress Warning.SURROGATE_KEY when fields are marked @NaturalId." - ); + .when( + () -> EqualsVerifier + .forClass(NaturalIdBusinessKeyPerson.class) + .suppress(Warning.SURROGATE_KEY) + .verify()) + .assertFailure() + .assertMessageContains( + "Precondition: you can't suppress Warning.SURROGATE_KEY when fields are marked @NaturalId."); } @Test public void fail_whenWithOnlyTheseFieldsIsUsed_givenWarningSurrogateKeyIsSuppressed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(JpaIdSurrogateKeyPerson.class) - .withOnlyTheseFields("socialSecurity") - .suppress(Warning.SURROGATE_KEY) - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "Precondition", - "you can't use withOnlyTheseFields when Warning.SURROGATE_KEY is suppressed." - ); + .when( + () -> EqualsVerifier + .forClass(JpaIdSurrogateKeyPerson.class) + .withOnlyTheseFields("socialSecurity") + .suppress(Warning.SURROGATE_KEY)) + .assertThrows(IllegalStateException.class) + .assertMessageContains( + "Precondition", + "you can't use withOnlyTheseFields when Warning.SURROGATE_KEY is suppressed."); } @Test public void fail_whenWithOnlyTheseFieldsIsUsed_givenWarningSurrogateKeyIsSuppressedInReverse() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(JpaIdSurrogateKeyPerson.class) - .suppress(Warning.SURROGATE_KEY) - .withOnlyTheseFields("socialSecurity") - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "Precondition", - "you can't use withOnlyTheseFields when Warning.SURROGATE_KEY is suppressed." - ); + .when( + () -> EqualsVerifier + .forClass(JpaIdSurrogateKeyPerson.class) + .suppress(Warning.SURROGATE_KEY) + .withOnlyTheseFields("socialSecurity")) + .assertThrows(IllegalStateException.class) + .assertMessageContains( + "Precondition", + "you can't use withOnlyTheseFields when Warning.SURROGATE_KEY is suppressed."); } @Test public void fail_whenFieldsAreIgnored_givenWarningSurrogateKeyIsSuppressed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(JpaIdSurrogateKeyPerson.class) - .withIgnoredFields("socialSecurity") - .suppress(Warning.SURROGATE_KEY) - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "Precondition: you can't use withIgnoredFields when Warning.SURROGATE_KEY is suppressed." - ); + .when( + () -> EqualsVerifier + .forClass(JpaIdSurrogateKeyPerson.class) + .withIgnoredFields("socialSecurity") + .suppress(Warning.SURROGATE_KEY)) + .assertThrows(IllegalStateException.class) + .assertMessageContains( + "Precondition: you can't use withIgnoredFields when Warning.SURROGATE_KEY is suppressed."); } @Test public void fail_whenFieldsAreIgnored_givenWarningSurrogateKeyIsSuppressedInReverse() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(JpaIdSurrogateKeyPerson.class) - .suppress(Warning.SURROGATE_KEY) - .withIgnoredFields("socialSecurity") - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "Precondition: you can't use withIgnoredFields when Warning.SURROGATE_KEY is suppressed." - ); + .when( + () -> EqualsVerifier + .forClass(JpaIdSurrogateKeyPerson.class) + .suppress(Warning.SURROGATE_KEY) + .withIgnoredFields("socialSecurity")) + .assertThrows(IllegalStateException.class) + .assertMessageContains( + "Precondition: you can't use withIgnoredFields when Warning.SURROGATE_KEY is suppressed."); } @Test public void fail_whenWithOnlyTheseFieldsIsUsed_givenFieldsAreMarkedWithNaturalId() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(NaturalIdBusinessKeyPerson.class) - .withOnlyTheseFields("socialSecurity") - .verify() - ) - .assertFailure() - .assertMessageContains( - "Precondition: you can't use withOnlyTheseFields when fields are marked with @NaturalId." - ); + .when( + () -> EqualsVerifier + .forClass(NaturalIdBusinessKeyPerson.class) + .withOnlyTheseFields("socialSecurity") + .verify()) + .assertFailure() + .assertMessageContains( + "Precondition: you can't use withOnlyTheseFields when fields are marked with @NaturalId."); } @Test public void fail_whenFieldsAreIgnored_givenFieldsAreMarkedWithNaturalId() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(NaturalIdBusinessKeyPerson.class) - .withIgnoredFields("socialSecurity") - .verify() - ) - .assertFailure() - .assertMessageContains( - "Precondition: you can't use withIgnoredFields when fields are marked with @NaturalId." - ); + .when( + () -> EqualsVerifier + .forClass(NaturalIdBusinessKeyPerson.class) + .withIgnoredFields("socialSecurity") + .verify()) + .assertFailure() + .assertMessageContains( + "Precondition: you can't use withIgnoredFields when fields are marked with @NaturalId."); } @Test public void fail_whenWarningVersionedEntityIsSuppressed_givenAFieldIsAnnotatedWithNaturalId() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(NaturalIdBusinessKeyPerson.class) - .suppress(Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY) - .verify() - ) - .assertFailure() - .assertMessageContains( - "Precondition: you can't suppress Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY when fields are marked with @NaturalId." - ); + .when( + () -> EqualsVerifier + .forClass(NaturalIdBusinessKeyPerson.class) + .suppress(Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY) + .verify()) + .assertFailure() + .assertMessageContains( + "Precondition: you can't suppress Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY when fields are marked with @NaturalId."); } @Test public void fail_whenWarningSurrogateKeyIsSuppressed_givenWarningSurrogateOrBusinessKeyIsAlsoSuppressed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(JpaIdBusinessKeyPerson.class) - .suppress(Warning.SURROGATE_KEY, Warning.SURROGATE_OR_BUSINESS_KEY) - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "Precondition", - "you can't suppress Warning.SURROGATE_KEY when Warning.SURROGATE_OR_BUSINESS_KEY is also suppressed." - ); + .when( + () -> EqualsVerifier + .forClass(JpaIdBusinessKeyPerson.class) + .suppress(Warning.SURROGATE_KEY, Warning.SURROGATE_OR_BUSINESS_KEY)) + .assertThrows(IllegalStateException.class) + .assertMessageContains( + "Precondition", + "you can't suppress Warning.SURROGATE_KEY when Warning.SURROGATE_OR_BUSINESS_KEY is also suppressed."); } @Test public void fail_whenAnIdAnnotationFromAnotherPackageIsUsed() { ExpectedException - .when(() -> EqualsVerifier.forClass(NonJpaIdBusinessKeyPerson.class).verify()) - .assertFailure() - .assertMessageContains("Significant fields"); + .when(() -> EqualsVerifier.forClass(NonJpaIdBusinessKeyPerson.class).verify()) + .assertFailure() + .assertMessageContains("Significant fields"); } @Test public void fail_whenANaturalIdAnnotationFromAnotherPackageIsUsed() { ExpectedException - .when(() -> - EqualsVerifier.forClass(NonHibernateNaturalIdBusinessKeyPerson.class).verify() - ) - .assertFailure() - .assertMessageContains("Significant fields"); + .when(() -> EqualsVerifier.forClass(NonHibernateNaturalIdBusinessKeyPerson.class).verify()) + .assertFailure() + .assertMessageContains("Significant fields"); } @Test @@ -418,10 +363,10 @@ public void succeed_whenEqualsIsImplementedInSuperclass_givenWarningSurrogateKey @Test public void succeed_whenEqualsUsesIdsAndNonIds_givenWarningSurrogateOrBusinessKeyIsSuppressed() { EqualsVerifier - .forClass(JpaIdDirtyTrackingPerson.class) - .suppress(Warning.SURROGATE_OR_BUSINESS_KEY) - .withOnlyTheseFields("id", "version", "isDirty") - .verify(); + .forClass(JpaIdDirtyTrackingPerson.class) + .suppress(Warning.SURROGATE_OR_BUSINESS_KEY) + .withOnlyTheseFields("id", "version", "isDirty") + .verify(); } static class JpaIdBusinessKeyPerson { @@ -433,12 +378,7 @@ static class JpaIdBusinessKeyPerson { private final String name; private final LocalDate birthdate; - public JpaIdBusinessKeyPerson( - UUID id, - String socialSecurity, - String name, - LocalDate birthdate - ) { + public JpaIdBusinessKeyPerson(UUID id, String socialSecurity, String name, LocalDate birthdate) { this.id = id; this.socialSecurity = socialSecurity; this.name = name; @@ -451,11 +391,9 @@ public final boolean equals(Object obj) { return false; } JpaIdBusinessKeyPerson other = (JpaIdBusinessKeyPerson) obj; - return ( - Objects.equals(socialSecurity, other.socialSecurity) && - Objects.equals(name, other.name) && - Objects.equals(birthdate, other.birthdate) - ); + return Objects.equals(socialSecurity, other.socialSecurity) + && Objects.equals(name, other.name) + && Objects.equals(birthdate, other.birthdate); } @Override @@ -473,12 +411,7 @@ static class JpaIdBusinessKeyPersonReorderedFields { @Id private final UUID id; - public JpaIdBusinessKeyPersonReorderedFields( - UUID id, - String socialSecurity, - String name, - LocalDate birthdate - ) { + public JpaIdBusinessKeyPersonReorderedFields(UUID id, String socialSecurity, String name, LocalDate birthdate) { this.id = id; this.socialSecurity = socialSecurity; this.name = name; @@ -490,13 +423,10 @@ public final boolean equals(Object obj) { if (!(obj instanceof JpaIdBusinessKeyPersonReorderedFields)) { return false; } - JpaIdBusinessKeyPersonReorderedFields other = - (JpaIdBusinessKeyPersonReorderedFields) obj; - return ( - Objects.equals(socialSecurity, other.socialSecurity) && - Objects.equals(name, other.name) && - Objects.equals(birthdate, other.birthdate) - ); + JpaIdBusinessKeyPersonReorderedFields other = (JpaIdBusinessKeyPersonReorderedFields) obj; + return Objects.equals(socialSecurity, other.socialSecurity) + && Objects.equals(name, other.name) + && Objects.equals(birthdate, other.birthdate); } @Override @@ -514,12 +444,7 @@ static class JpaIdSurrogateKeyPerson { private final String name; private final LocalDate birthdate; - public JpaIdSurrogateKeyPerson( - UUID id, - String socialSecurity, - String name, - LocalDate birthdate - ) { + public JpaIdSurrogateKeyPerson(UUID id, String socialSecurity, String name, LocalDate birthdate) { this.id = id; this.socialSecurity = socialSecurity; this.name = name; @@ -551,11 +476,10 @@ static class JpaIdSurrogateKeyPersonReorderedFields { private final UUID id; public JpaIdSurrogateKeyPersonReorderedFields( - UUID id, - String socialSecurity, - String name, - LocalDate birthdate - ) { + UUID id, + String socialSecurity, + String name, + LocalDate birthdate) { this.id = id; this.socialSecurity = socialSecurity; this.name = name; @@ -567,8 +491,7 @@ public final boolean equals(Object obj) { if (!(obj instanceof JpaIdSurrogateKeyPersonReorderedFields)) { return false; } - JpaIdSurrogateKeyPersonReorderedFields other = - (JpaIdSurrogateKeyPersonReorderedFields) obj; + JpaIdSurrogateKeyPersonReorderedFields other = (JpaIdSurrogateKeyPersonReorderedFields) obj; return Objects.equals(id, other.id); } @@ -587,12 +510,7 @@ static class JpaIdValueKeyPerson { private final String name; private final LocalDate birthdate; - public JpaIdValueKeyPerson( - UUID id, - String socialSecurity, - String name, - LocalDate birthdate - ) { + public JpaIdValueKeyPerson(UUID id, String socialSecurity, String name, LocalDate birthdate) { this.id = id; this.socialSecurity = socialSecurity; this.name = name; @@ -605,12 +523,10 @@ public final boolean equals(Object obj) { return false; } JpaIdValueKeyPerson other = (JpaIdValueKeyPerson) obj; - return ( - Objects.equals(id, other.id) && - Objects.equals(socialSecurity, other.socialSecurity) && - Objects.equals(name, other.name) && - Objects.equals(birthdate, other.birthdate) - ); + return Objects.equals(id, other.id) + && Objects.equals(socialSecurity, other.socialSecurity) + && Objects.equals(name, other.name) + && Objects.equals(birthdate, other.birthdate); } @Override @@ -628,12 +544,7 @@ static class JpaIdValueKeyPersonReorderedFields { @Id private final UUID id; - public JpaIdValueKeyPersonReorderedFields( - UUID id, - String socialSecurity, - String name, - LocalDate birthdate - ) { + public JpaIdValueKeyPersonReorderedFields(UUID id, String socialSecurity, String name, LocalDate birthdate) { this.id = id; this.socialSecurity = socialSecurity; this.name = name; @@ -646,12 +557,10 @@ public final boolean equals(Object obj) { return false; } JpaIdValueKeyPersonReorderedFields other = (JpaIdValueKeyPersonReorderedFields) obj; - return ( - Objects.equals(socialSecurity, other.socialSecurity) && - Objects.equals(name, other.name) && - Objects.equals(birthdate, other.birthdate) && - Objects.equals(id, other.id) - ); + return Objects.equals(socialSecurity, other.socialSecurity) + && Objects.equals(name, other.name) + && Objects.equals(birthdate, other.birthdate) + && Objects.equals(id, other.id); } @Override @@ -669,12 +578,7 @@ static class JpaEmbeddedIdBusinessKeyPerson { private final String name; private final LocalDate birthdate; - public JpaEmbeddedIdBusinessKeyPerson( - UUID id, - String socialSecurity, - String name, - LocalDate birthdate - ) { + public JpaEmbeddedIdBusinessKeyPerson(UUID id, String socialSecurity, String name, LocalDate birthdate) { this.id = id; this.socialSecurity = socialSecurity; this.name = name; @@ -687,11 +591,9 @@ public final boolean equals(Object obj) { return false; } JpaEmbeddedIdBusinessKeyPerson other = (JpaEmbeddedIdBusinessKeyPerson) obj; - return ( - Objects.equals(socialSecurity, other.socialSecurity) && - Objects.equals(name, other.name) && - Objects.equals(birthdate, other.birthdate) - ); + return Objects.equals(socialSecurity, other.socialSecurity) + && Objects.equals(name, other.name) + && Objects.equals(birthdate, other.birthdate); } @Override @@ -709,12 +611,7 @@ static class JpaEmbeddedIdSurrogateKeyPerson { private final String name; private final LocalDate birthdate; - public JpaEmbeddedIdSurrogateKeyPerson( - UUID id, - String socialSecurity, - String name, - LocalDate birthdate - ) { + public JpaEmbeddedIdSurrogateKeyPerson(UUID id, String socialSecurity, String name, LocalDate birthdate) { this.id = id; this.socialSecurity = socialSecurity; this.name = name; @@ -747,12 +644,7 @@ static class NaturalIdBusinessKeyPerson { private final String name; private final LocalDate birthdate; - public NaturalIdBusinessKeyPerson( - UUID id, - String socialSecurity, - String name, - LocalDate birthdate - ) { + public NaturalIdBusinessKeyPerson(UUID id, String socialSecurity, String name, LocalDate birthdate) { this.id = id; this.socialSecurity = socialSecurity; this.name = name; @@ -785,11 +677,10 @@ static class NaturalIdWithoutJpaIdBusinessKeyPerson { private final LocalDate birthdate; public NaturalIdWithoutJpaIdBusinessKeyPerson( - UUID id, - String socialSecurity, - String name, - LocalDate birthdate - ) { + UUID id, + String socialSecurity, + String name, + LocalDate birthdate) { this.id = id; this.socialSecurity = socialSecurity; this.name = name; @@ -801,8 +692,7 @@ public final boolean equals(Object obj) { if (!(obj instanceof NaturalIdWithoutJpaIdBusinessKeyPerson)) { return false; } - NaturalIdWithoutJpaIdBusinessKeyPerson other = - (NaturalIdWithoutJpaIdBusinessKeyPerson) obj; + NaturalIdWithoutJpaIdBusinessKeyPerson other = (NaturalIdWithoutJpaIdBusinessKeyPerson) obj; return Objects.equals(socialSecurity, other.socialSecurity); } @@ -821,12 +711,7 @@ static class JpaIdBusinessKeyPersonDoesntUseName { private final String name; private final LocalDate birthdate; - public JpaIdBusinessKeyPersonDoesntUseName( - UUID id, - String socialSecurity, - String name, - LocalDate birthdate - ) { + public JpaIdBusinessKeyPersonDoesntUseName(UUID id, String socialSecurity, String name, LocalDate birthdate) { this.id = id; this.socialSecurity = socialSecurity; this.name = name; @@ -839,10 +724,7 @@ public final boolean equals(Object obj) { return false; } JpaIdBusinessKeyPersonDoesntUseName other = (JpaIdBusinessKeyPersonDoesntUseName) obj; - return ( - Objects.equals(socialSecurity, other.socialSecurity) && - Objects.equals(birthdate, other.birthdate) - ); + return Objects.equals(socialSecurity, other.socialSecurity) && Objects.equals(birthdate, other.birthdate); } @Override @@ -867,11 +749,9 @@ public final boolean equals(Object obj) { return false; } JpaIdBusinessKeyPersonEntity other = (JpaIdBusinessKeyPersonEntity) obj; - return ( - Objects.equals(socialSecurity, other.socialSecurity) && - Objects.equals(name, other.name) && - Objects.equals(birthdate, other.birthdate) - ); + return Objects.equals(socialSecurity, other.socialSecurity) + && Objects.equals(name, other.name) + && Objects.equals(birthdate, other.birthdate); } @Override @@ -916,12 +796,7 @@ static class NonJpaIdBusinessKeyPerson { private final String name; private final LocalDate birthdate; - public NonJpaIdBusinessKeyPerson( - UUID id, - String socialSecurity, - String name, - LocalDate birthdate - ) { + public NonJpaIdBusinessKeyPerson(UUID id, String socialSecurity, String name, LocalDate birthdate) { this.id = id; this.socialSecurity = socialSecurity; this.name = name; @@ -934,11 +809,9 @@ public final boolean equals(Object obj) { return false; } NonJpaIdBusinessKeyPerson other = (NonJpaIdBusinessKeyPerson) obj; - return ( - Objects.equals(socialSecurity, other.socialSecurity) && - Objects.equals(name, other.name) && - Objects.equals(birthdate, other.birthdate) - ); + return Objects.equals(socialSecurity, other.socialSecurity) + && Objects.equals(name, other.name) + && Objects.equals(birthdate, other.birthdate); } @Override @@ -959,11 +832,10 @@ static class NonHibernateNaturalIdBusinessKeyPerson { private final LocalDate birthdate; public NonHibernateNaturalIdBusinessKeyPerson( - UUID id, - String socialSecurity, - String name, - LocalDate birthdate - ) { + UUID id, + String socialSecurity, + String name, + LocalDate birthdate) { this.id = id; this.socialSecurity = socialSecurity; this.name = name; @@ -975,8 +847,7 @@ public final boolean equals(Object obj) { if (!(obj instanceof NonHibernateNaturalIdBusinessKeyPerson)) { return false; } - NonHibernateNaturalIdBusinessKeyPerson other = - (NonHibernateNaturalIdBusinessKeyPerson) obj; + NonHibernateNaturalIdBusinessKeyPerson other = (NonHibernateNaturalIdBusinessKeyPerson) obj; return Objects.equals(socialSecurity, other.socialSecurity); } @@ -1023,12 +894,7 @@ static class MethodAnnotatedBusinessKeyPerson { private final String name; private final LocalDate birthdate; - public MethodAnnotatedBusinessKeyPerson( - UUID id, - String socialSecurity, - String name, - LocalDate birthdate - ) { + public MethodAnnotatedBusinessKeyPerson(UUID id, String socialSecurity, String name, LocalDate birthdate) { this.id = id; this.socialSecurity = socialSecurity; this.name = name; @@ -1121,11 +987,9 @@ public final boolean equals(Object obj) { return false; } JpaIdDirtyTrackingPerson other = (JpaIdDirtyTrackingPerson) obj; - return ( - Objects.equals(id, other.id) && - Objects.equals(version, other.version) && - Objects.equals(isDirty, other.isDirty) - ); + return Objects.equals(id, other.id) + && Objects.equals(version, other.version) + && Objects.equals(isDirty, other.isDirty); } @Override diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/JpaLazyEntityTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/JpaLazyEntityTest.java index e55f2c3eb..6b7fccf6f 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/JpaLazyEntityTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/JpaLazyEntityTest.java @@ -2,6 +2,7 @@ import java.util.Arrays; import java.util.Objects; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; @@ -20,9 +21,9 @@ public void gettersAreUsed() { @Test public void basicGetterAbsent() { ExpectedException - .when(() -> EqualsVerifier.forClass(LazyFieldWithoutGetterContainer.class).verify()) - .assertFailure() - .assertMessageContains("doesn't contain getter getBasic() for field basic"); + .when(() -> EqualsVerifier.forClass(LazyFieldWithoutGetterContainer.class).verify()) + .assertFailure() + .assertMessageContains("doesn't contain getter getBasic() for field basic"); } @Test @@ -32,18 +33,15 @@ public void basicGetterNotUsed_givenEagerLoading() { @Test public void basicGetterNotUsed_givenCorrespondingFieldIgnored() { - EqualsVerifier - .forClass(CorrectBasicJpaIgnoredLazyFieldContainer.class) - .withIgnoredFields("basic") - .verify(); + EqualsVerifier.forClass(CorrectBasicJpaIgnoredLazyFieldContainer.class).withIgnoredFields("basic").verify(); } @Test public void basicGetterNotUsed_givenWarningSuppressed() { EqualsVerifier - .forClass(CorrectBasicJpaIgnoredLazyFieldContainer.class) - .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) - .verify(); + .forClass(CorrectBasicJpaIgnoredLazyFieldContainer.class) + .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) + .verify(); } @Test @@ -102,71 +100,49 @@ public void lazyGettersPickedUpInSuper() { @Test public void constantHashCode_givenStrictHashCodeSuppressed() { - EqualsVerifier - .forClass(ConstantHashCodeContainer.class) - .suppress(Warning.STRICT_HASHCODE) - .verify(); + EqualsVerifier.forClass(ConstantHashCodeContainer.class).suppress(Warning.STRICT_HASHCODE).verify(); } @Test public void differentCodingStyle_single() { EqualsVerifier - .forClass(DifferentCodingStyleContainer.class) - .withFieldnameToGetterConverter(fn -> - "get" + Character.toUpperCase(fn.charAt(2)) + fn.substring(3) - ) - .verify(); + .forClass(DifferentCodingStyleContainer.class) + .withFieldnameToGetterConverter(fn -> "get" + Character.toUpperCase(fn.charAt(2)) + fn.substring(3)) + .verify(); } @Test public void differentCodingStyle_configured() { EqualsVerifier - .configure() - .withFieldnameToGetterConverter(fn -> - "get" + Character.toUpperCase(fn.charAt(2)) + fn.substring(3) - ) - .forClass(DifferentCodingStyleContainer.class) - .verify(); + .configure() + .withFieldnameToGetterConverter(fn -> "get" + Character.toUpperCase(fn.charAt(2)) + fn.substring(3)) + .forClass(DifferentCodingStyleContainer.class) + .verify(); } @Test public void differentCodingStyle_multiple() { EqualsVerifier - .forClasses(Arrays.asList(DifferentCodingStyleContainer.class)) - .withFieldnameToGetterConverter(fn -> - "get" + Character.toUpperCase(fn.charAt(2)) + fn.substring(3) - ) - .verify(); + .forClasses(Arrays.asList(DifferentCodingStyleContainer.class)) + .withFieldnameToGetterConverter(fn -> "get" + Character.toUpperCase(fn.charAt(2)) + fn.substring(3)) + .verify(); } @Test public void getterUsedForGeneratedId() { + EqualsVerifier.forClass(CorrectGeneratedJpaIdContainer.class).suppress(Warning.SURROGATE_KEY).verify(); EqualsVerifier - .forClass(CorrectGeneratedJpaIdContainer.class) - .suppress(Warning.SURROGATE_KEY) - .verify(); - EqualsVerifier - .forClass(CorrectGeneratedJpaIdContainer.class) - .suppress(Warning.SURROGATE_OR_BUSINESS_KEY) - .verify(); + .forClass(CorrectGeneratedJpaIdContainer.class) + .suppress(Warning.SURROGATE_OR_BUSINESS_KEY) + .verify(); } @Test public void getterNotUsedForGeneratedId() { getterNotUsed(IncorrectGeneratedJpaIdContainer.class, "equals", Warning.SURROGATE_KEY); - getterNotUsed_warningSuppressed( - IncorrectGeneratedJpaIdContainer.class, - Warning.SURROGATE_KEY - ); - getterNotUsed( - IncorrectGeneratedJpaIdContainer.class, - "equals", - Warning.SURROGATE_OR_BUSINESS_KEY - ); - getterNotUsed_warningSuppressed( - IncorrectGeneratedJpaIdContainer.class, - Warning.SURROGATE_OR_BUSINESS_KEY - ); + getterNotUsed_warningSuppressed(IncorrectGeneratedJpaIdContainer.class, Warning.SURROGATE_KEY); + getterNotUsed(IncorrectGeneratedJpaIdContainer.class, "equals", Warning.SURROGATE_OR_BUSINESS_KEY); + getterNotUsed_warningSuppressed(IncorrectGeneratedJpaIdContainer.class, Warning.SURROGATE_OR_BUSINESS_KEY); } @Test @@ -181,17 +157,13 @@ public void finalEntitiesArentLazy() { private void getterNotUsed(Class type, String method, Warning... additionalWarnings) { ExpectedException - .when(() -> EqualsVerifier.forClass(type).suppress(additionalWarnings).verify()) - .assertFailure() - .assertMessageContains("JPA Entity", method, "direct reference"); + .when(() -> EqualsVerifier.forClass(type).suppress(additionalWarnings).verify()) + .assertFailure() + .assertMessageContains("JPA Entity", method, "direct reference"); } private void getterNotUsed_warningSuppressed(Class type, Warning... additionalWarnings) { - EqualsVerifier - .forClass(type) - .suppress(Warning.JPA_GETTER) - .suppress(additionalWarnings) - .verify(); + EqualsVerifier.forClass(type).suppress(Warning.JPA_GETTER).suppress(additionalWarnings).verify(); } @Entity @@ -245,26 +217,24 @@ public boolean equals(Object obj) { return false; } CorrectJpaLazyFieldContainer other = (CorrectJpaLazyFieldContainer) obj; - return ( - Objects.equals(getBasic(), other.getBasic()) && - Objects.equals(getOneToOne(), other.getOneToOne()) && - Objects.equals(getOneToMany(), other.getOneToMany()) && - Objects.equals(getManyToOne(), other.getManyToOne()) && - Objects.equals(getManyToMany(), other.getManyToMany()) && - Objects.equals(getElementCollection(), other.getElementCollection()) - ); + return Objects.equals(getBasic(), other.getBasic()) + && Objects.equals(getOneToOne(), other.getOneToOne()) + && Objects.equals(getOneToMany(), other.getOneToMany()) + && Objects.equals(getManyToOne(), other.getManyToOne()) + && Objects.equals(getManyToMany(), other.getManyToMany()) + && Objects.equals(getElementCollection(), other.getElementCollection()); } @Override public int hashCode() { - return Objects.hash( - getBasic(), - getOneToOne(), - getOneToMany(), - getManyToOne(), - getManyToMany(), - getElementCollection() - ); + return Objects + .hash( + getBasic(), + getOneToOne(), + getOneToMany(), + getManyToOne(), + getManyToMany(), + getElementCollection()); } } @@ -331,8 +301,7 @@ public boolean equals(Object obj) { if (!(obj instanceof CorrectBasicJpaIgnoredLazyFieldContainer)) { return false; } - CorrectBasicJpaIgnoredLazyFieldContainer other = - (CorrectBasicJpaIgnoredLazyFieldContainer) obj; + CorrectBasicJpaIgnoredLazyFieldContainer other = (CorrectBasicJpaIgnoredLazyFieldContainer) obj; return Objects.equals(somethingElse, other.somethingElse); } @@ -382,8 +351,7 @@ public boolean equals(Object obj) { if (!(obj instanceof IncorrectBasicJpaLazyFieldContainerHashCode)) { return false; } - IncorrectBasicJpaLazyFieldContainerHashCode other = - (IncorrectBasicJpaLazyFieldContainerHashCode) obj; + IncorrectBasicJpaLazyFieldContainerHashCode other = (IncorrectBasicJpaLazyFieldContainerHashCode) obj; return Objects.equals(getBasic(), other.getBasic()); } @@ -433,8 +401,7 @@ public boolean equals(Object obj) { if (!(obj instanceof IncorrectOneToOneJpaLazyFieldContainer)) { return false; } - IncorrectOneToOneJpaLazyFieldContainer other = - (IncorrectOneToOneJpaLazyFieldContainer) obj; + IncorrectOneToOneJpaLazyFieldContainer other = (IncorrectOneToOneJpaLazyFieldContainer) obj; return Objects.equals(oneToOne, other.oneToOne); } @@ -459,8 +426,7 @@ public boolean equals(Object obj) { if (!(obj instanceof IncorrectOneToManyJpaLazyFieldContainer)) { return false; } - IncorrectOneToManyJpaLazyFieldContainer other = - (IncorrectOneToManyJpaLazyFieldContainer) obj; + IncorrectOneToManyJpaLazyFieldContainer other = (IncorrectOneToManyJpaLazyFieldContainer) obj; return Objects.equals(oneToMany, other.oneToMany); } @@ -485,8 +451,7 @@ public boolean equals(Object obj) { if (!(obj instanceof IncorrectManyToOneJpaLazyFieldContainer)) { return false; } - IncorrectManyToOneJpaLazyFieldContainer other = - (IncorrectManyToOneJpaLazyFieldContainer) obj; + IncorrectManyToOneJpaLazyFieldContainer other = (IncorrectManyToOneJpaLazyFieldContainer) obj; return Objects.equals(manyToOne, other.manyToOne); } @@ -511,8 +476,7 @@ public boolean equals(Object obj) { if (!(obj instanceof IncorrectManyToManyJpaLazyFieldContainer)) { return false; } - IncorrectManyToManyJpaLazyFieldContainer other = - (IncorrectManyToManyJpaLazyFieldContainer) obj; + IncorrectManyToManyJpaLazyFieldContainer other = (IncorrectManyToManyJpaLazyFieldContainer) obj; return Objects.equals(manyToMany, other.manyToMany); } @@ -538,7 +502,7 @@ public boolean equals(Object obj) { return false; } IncorrectElementCollectionJpaLazyFieldContainer other = - (IncorrectElementCollectionJpaLazyFieldContainer) obj; + (IncorrectElementCollectionJpaLazyFieldContainer) obj; return Objects.equals(elementCollection, other.elementCollection); } @@ -613,10 +577,8 @@ public boolean equals(Object obj) { return false; } ConstantHashCodeContainer other = (ConstantHashCodeContainer) obj; - return ( - Objects.equals(getOneToMany(), other.getOneToMany()) && - Objects.equals(getManyToOne(), other.getManyToOne()) - ); + return Objects.equals(getOneToMany(), other.getOneToMany()) + && Objects.equals(getManyToOne(), other.getManyToOne()); } @Override @@ -651,10 +613,8 @@ public boolean equals(Object obj) { return false; } DifferentCodingStyleContainer other = (DifferentCodingStyleContainer) obj; - return ( - Objects.equals(getOneToMany(), other.getOneToMany()) && - Objects.equals(getManyToOne(), other.getManyToOne()) - ); + return Objects.equals(getOneToMany(), other.getOneToMany()) + && Objects.equals(getManyToOne(), other.getManyToOne()); } @Override diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/LombokLazyEqualsAndHashcodeTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/LombokLazyEqualsAndHashcodeTest.java index 3b23eabb6..981ecbb44 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/LombokLazyEqualsAndHashcodeTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/LombokLazyEqualsAndHashcodeTest.java @@ -17,62 +17,47 @@ public class LombokLazyEqualsAndHashcodeTest { @Test void testWithLombokCachedHashCode() { EqualsVerifier - .forClass(LazyPojo.class) - .withLombokCachedHashCode(new LazyPojo("a", new Object())) - .suppress(Warning.STRICT_INHERITANCE) - .verify(); + .forClass(LazyPojo.class) + .withLombokCachedHashCode(new LazyPojo("a", new Object())) + .suppress(Warning.STRICT_INHERITANCE) + .verify(); } @Test void testDefaultEqualsVerifierFailsForCachedLombokEqualsAndHashcode() { final AssertionError error = assertThrows( AssertionError.class, - () -> - EqualsVerifier - .forClass(LazyPojo.class) - .suppress(Warning.STRICT_INHERITANCE) - .verify() - ); - assertThat( - error.getMessage(), - containsString("hashCode relies on $hashCodeCache, but equals does not.") - ); + () -> EqualsVerifier.forClass(LazyPojo.class).suppress(Warning.STRICT_INHERITANCE).verify()); + assertThat(error.getMessage(), containsString("hashCode relies on $hashCodeCache, but equals does not.")); } @Test void testDefaultEqualsVerifierFailsForCachedLombokEqualsAndHashcodeWhenUsingWithCachedHashCode() { final IllegalArgumentException error = assertThrows( IllegalArgumentException.class, - () -> - EqualsVerifier + () -> EqualsVerifier .forClass(LazyPojo.class) .suppress(Warning.STRICT_INHERITANCE) - .withCachedHashCode( - "$hashCodeCache", - "hashCode", - new LazyPojo("bar", new Object()) - ) - .verify() - ); + .withCachedHashCode("$hashCodeCache", "hashCode", new LazyPojo("bar", new Object())) + .verify()); assertThat( error.getMessage(), containsString( - "Cached hashCode: Could not find calculateHashCodeMethod: must be 'private int hashCode()'" - ) - ); + "Cached hashCode: Could not find calculateHashCodeMethod: must be 'private int hashCode()'")); } /** * This class has been generated with Lombok (1.18.20). It is equivalent to: + * *

-     *   @RequiredArgsConstructor
-     *   @EqualsAndHashCode(cacheStrategy = EqualsAndHashCode.CacheStrategy.LAZY)
-     *   public class LazyPojo {
+     * @RequiredArgsConstructor
+     * @EqualsAndHashCode(cacheStrategy = EqualsAndHashCode.CacheStrategy.LAZY)
+     * public class LazyPojo {
      *
      *     private final String foo;
      *
      *     private final Object bar;
-     *   }
+     * }
      * 
*/ @SuppressWarnings({ "RedundantIfStatement", "EqualsReplaceableByObjectsCall" }) @@ -90,16 +75,21 @@ public LazyPojo(String foo, Object bar) { @Override public boolean equals(final Object o) { - if (o == this) return true; - if (!(o instanceof LazyPojo)) return false; + if (o == this) + return true; + if (!(o instanceof LazyPojo)) + return false; final LazyPojo other = (LazyPojo) o; - if (!other.canEqual(this)) return false; + if (!other.canEqual(this)) + return false; final Object this$foo = this.foo; final Object other$foo = other.foo; - if (this$foo == null ? other$foo != null : !this$foo.equals(other$foo)) return false; + if (this$foo == null ? other$foo != null : !this$foo.equals(other$foo)) + return false; final Object this$bar = this.bar; final Object other$bar = other.bar; - if (this$bar == null ? other$bar != null : !this$bar.equals(other$bar)) return false; + if (this$bar == null ? other$bar != null : !this$bar.equals(other$bar)) + return false; return true; } @@ -111,7 +101,8 @@ protected boolean canEqual(Object other) { public int hashCode() { if (this.$hashCodeCache != 0) { return this.$hashCodeCache; - } else { + } + else { final int PRIME = 59; int result = 1; final Object $foo = this.foo; diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/RelaxedEqualsPreconditionTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/RelaxedEqualsPreconditionTest.java index 1a8a7ae43..4afc6d2ea 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/RelaxedEqualsPreconditionTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/RelaxedEqualsPreconditionTest.java @@ -12,8 +12,7 @@ public class RelaxedEqualsPreconditionTest { private static final String DIFFERENT_CLASSES = "are of different classes"; private static final String TWO_IDENTICAL_OBJECTS_APPEAR = "two identical objects appear"; private static final String NOT_ALL_EQUAL_OBJECT_ARE_EQUAL = "not all equal objects are equal"; - private static final String EQUAL_IS_UNEQUAL = - "an equal example also appears as unequal example."; + private static final String EQUAL_IS_UNEQUAL = "an equal example also appears as unequal example."; private static final String OBJECT_APPEARS_TWICE = "the same object appears twice"; private static final String TWO_OBJECTS_ARE_EQUAL = "two objects are equal to each other"; @@ -31,151 +30,116 @@ public void setup() { @Test public void throw_whenTheFirstExampleIsNull() { ExpectedException - .when(() -> EqualsVerifier.forRelaxedEqualExamples(null, blue)) - .assertThrows(IllegalArgumentException.class) - .assertMessageContains("First example is null."); + .when(() -> EqualsVerifier.forRelaxedEqualExamples(null, blue)) + .assertThrows(IllegalArgumentException.class) + .assertMessageContains("First example is null."); } @Test public void throw_whenTheSecondExampleIsNull() { ExpectedException - .when(() -> EqualsVerifier.forRelaxedEqualExamples(red, null)) - .assertThrows(IllegalArgumentException.class) - .assertMessageContains("Second example is null."); + .when(() -> EqualsVerifier.forRelaxedEqualExamples(red, null)) + .assertThrows(IllegalArgumentException.class) + .assertMessageContains("Second example is null."); } @Test public void succeed_whenTheVarargArrayIsNull() { - EqualsVerifier - .forRelaxedEqualExamples(red, blue, (Multiple[]) null) - .andUnequalExample(green) - .verify(); + EqualsVerifier.forRelaxedEqualExamples(red, blue, (Multiple[]) null).andUnequalExample(green).verify(); } @Test public void fail_whenAVarargParameterIsNull() { Multiple another = new Multiple(-1, -2); ExpectedException - .when(() -> EqualsVerifier.forRelaxedEqualExamples(red, blue, another, null)) - .assertThrows(IllegalArgumentException.class) - .assertMessageContains("One of the examples is null."); + .when(() -> EqualsVerifier.forRelaxedEqualExamples(red, blue, another, null)) + .assertThrows(IllegalArgumentException.class) + .assertMessageContains("One of the examples is null."); } @Test public void fail_whenTheUnequalExampleIsNull() { ExpectedException - .when(() -> EqualsVerifier.forRelaxedEqualExamples(red, blue).andUnequalExample(null)) - .assertThrows(IllegalArgumentException.class) - .assertMessageContains("First example is null."); + .when(() -> EqualsVerifier.forRelaxedEqualExamples(red, blue).andUnequalExample(null)) + .assertThrows(IllegalArgumentException.class) + .assertMessageContains("First example is null."); } @Test public void succeed_whenTheUnequalVarargArrayIsNull() { - EqualsVerifier - .forRelaxedEqualExamples(red, blue) - .andUnequalExamples(green, (Multiple[]) null) - .verify(); + EqualsVerifier.forRelaxedEqualExamples(red, blue).andUnequalExamples(green, (Multiple[]) null).verify(); } @Test public void fail_whenAnUnequalVarargParameterIsNull() { Multiple another = new Multiple(3, 3); ExpectedException - .when(() -> - EqualsVerifier - .forRelaxedEqualExamples(red, blue) - .andUnequalExamples(green, another, null) - ) - .assertThrows(IllegalArgumentException.class); + .when(() -> EqualsVerifier.forRelaxedEqualExamples(red, blue).andUnequalExamples(green, another, null)) + .assertThrows(IllegalArgumentException.class); } @Test public void fail_whenEqualExamplesAreOfDifferentRuntimeTypes() { SubMultiple sm = new SubMultiple(1, 2); ExpectedException - .when(() -> - EqualsVerifier.forRelaxedEqualExamples(sm, red).andUnequalExample(green).verify() - ) - .assertFailure() - .assertMessageContains( - PRECONDITION, - DIFFERENT_CLASSES, - SubMultiple.class.getSimpleName(), - Multiple.class.getSimpleName() - ); + .when(() -> EqualsVerifier.forRelaxedEqualExamples(sm, red).andUnequalExample(green).verify()) + .assertFailure() + .assertMessageContains( + PRECONDITION, + DIFFERENT_CLASSES, + SubMultiple.class.getSimpleName(), + Multiple.class.getSimpleName()); } @Test public void fail_whenTheSameExampleIsGivenTwice() { ExpectedException - .when(() -> - EqualsVerifier.forRelaxedEqualExamples(red, red).andUnequalExample(green).verify() - ) - .assertFailure() - .assertMessageContains( - PRECONDITION, - OBJECT_APPEARS_TWICE, - Multiple.class.getSimpleName() - ); + .when(() -> EqualsVerifier.forRelaxedEqualExamples(red, red).andUnequalExample(green).verify()) + .assertFailure() + .assertMessageContains(PRECONDITION, OBJECT_APPEARS_TWICE, Multiple.class.getSimpleName()); } @Test public void fail_whenTwoExamplesAreIdentical() { Multiple aa = new Multiple(1, 2); ExpectedException - .when(() -> - EqualsVerifier.forRelaxedEqualExamples(red, aa).andUnequalExample(green).verify() - ) - .assertFailure() - .assertMessageContains( - PRECONDITION, - TWO_IDENTICAL_OBJECTS_APPEAR, - Multiple.class.getSimpleName() - ); + .when(() -> EqualsVerifier.forRelaxedEqualExamples(red, aa).andUnequalExample(green).verify()) + .assertFailure() + .assertMessageContains(PRECONDITION, TWO_IDENTICAL_OBJECTS_APPEAR, Multiple.class.getSimpleName()); } @Test public void fail_whenTwoExamplesAreNotEqualAtAll() { Multiple aa = new Multiple(42, 42); ExpectedException - .when(() -> - EqualsVerifier.forRelaxedEqualExamples(red, aa).andUnequalExample(green).verify() - ) - .assertFailure() - .assertMessageContains( - PRECONDITION, - NOT_ALL_EQUAL_OBJECT_ARE_EQUAL, - Multiple.class.getSimpleName() - ); + .when(() -> EqualsVerifier.forRelaxedEqualExamples(red, aa).andUnequalExample(green).verify()) + .assertFailure() + .assertMessageContains(PRECONDITION, NOT_ALL_EQUAL_OBJECT_ARE_EQUAL, Multiple.class.getSimpleName()); } @Test public void fail_whenAnEqualExampleIsAlsoGivenAsAnUnequalExample() { ExpectedException - .when(() -> EqualsVerifier.forRelaxedEqualExamples(red, green).andUnequalExample(green)) - .assertThrows(IllegalStateException.class) - .assertMessageContains(PRECONDITION, EQUAL_IS_UNEQUAL); + .when(() -> EqualsVerifier.forRelaxedEqualExamples(red, green).andUnequalExample(green)) + .assertThrows(IllegalStateException.class) + .assertMessageContains(PRECONDITION, EQUAL_IS_UNEQUAL); } @Test public void fail_whenTheSameUnequalExampleIsGivenTwice() { ExpectedException - .when(() -> - EqualsVerifier.forRelaxedEqualExamples(red, blue).andUnequalExamples(green, green) - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains(PRECONDITION, TWO_OBJECTS_ARE_EQUAL); + .when(() -> EqualsVerifier.forRelaxedEqualExamples(red, blue).andUnequalExamples(green, green)) + .assertThrows(IllegalStateException.class) + .assertMessageContains(PRECONDITION, TWO_OBJECTS_ARE_EQUAL); } @Test public void fail_whenTwoUnequalExamplesAreEqualToEachOther() { Multiple xx = new Multiple(2, 2); ExpectedException - .when(() -> - EqualsVerifier.forRelaxedEqualExamples(red, blue).andUnequalExamples(green, xx) - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains(PRECONDITION, TWO_OBJECTS_ARE_EQUAL); + .when(() -> EqualsVerifier.forRelaxedEqualExamples(red, blue).andUnequalExamples(green, xx)) + .assertThrows(IllegalStateException.class) + .assertMessageContains(PRECONDITION, TWO_OBJECTS_ARE_EQUAL); } public static class SubMultiple extends Multiple { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/RelaxedEqualsTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/RelaxedEqualsTest.java index b00de8265..c2a23e19a 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/RelaxedEqualsTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/RelaxedEqualsTest.java @@ -22,9 +22,9 @@ public void setup() { @Test public void fail_whenObjectsWithDifferentFieldsAreEqual() { ExpectedException - .when(() -> EqualsVerifier.forClass(Multiple.class).verify()) - .assertFailure() - .assertMessageContains("Significant fields"); + .when(() -> EqualsVerifier.forClass(Multiple.class).verify()) + .assertFailure() + .assertMessageContains("Significant fields"); } @Test @@ -35,23 +35,17 @@ public void succeed_whenObjectsWithDifferentFieldsAreEqual_givenTheyAreGivenAsRe @Test public void fail_whenTheSameObjectIsGivenAsAnUnequalExample() { ExpectedException - .when(() -> EqualsVerifier.forRelaxedEqualExamples(a, b).andUnequalExamples(a)) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "Precondition", - "an equal example also appears as unequal example." - ); + .when(() -> EqualsVerifier.forRelaxedEqualExamples(a, b).andUnequalExamples(a)) + .assertThrows(IllegalStateException.class) + .assertMessageContains("Precondition", "an equal example also appears as unequal example."); } @Test public void succeed_whenAnUnusedFieldIsNull_givenItIsGivenAsARelaxedEqualExample() { EqualsVerifier - .forRelaxedEqualExamples( - new NullContainingSubMultiple(1, 2), - new NullContainingSubMultiple(2, 1) - ) - .andUnequalExample(new NullContainingSubMultiple(2, 2)) - .verify(); + .forRelaxedEqualExamples(new NullContainingSubMultiple(1, 2), new NullContainingSubMultiple(2, 1)) + .andUnequalExample(new NullContainingSubMultiple(2, 2)) + .verify(); } public class NullContainingSubMultiple extends Multiple { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/SimpleEqualsVerifierTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/SimpleEqualsVerifierTest.java index 5a446258e..abe6d9f11 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/SimpleEqualsVerifierTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/SimpleEqualsVerifierTest.java @@ -1,6 +1,7 @@ package nl.jqno.equalsverifier.integration.extra_features; import java.util.Objects; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; @@ -17,103 +18,77 @@ public void succeed_whenTestingClass_givenASimpleEqualsVerifier() { @Test public void succeed_whenTestingClassesRecursively_givenASimpleEqualsVerifier() { EqualsVerifier - .simple() - .forPackage("nl.jqno.equalsverifier.integration.extra_features.simple_package", true) - .verify(); + .simple() + .forPackage("nl.jqno.equalsverifier.integration.extra_features.simple_package", true) + .verify(); } @Test public void succeed_whenTestingClassesThatMustExtendSomething_givenASimpleEqualsVerifier() { EqualsVerifier - .simple() - .forPackage( - "nl.jqno.equalsverifier.integration.extra_features.simple_package", - Object.class - ) - .verify(); + .simple() + .forPackage("nl.jqno.equalsverifier.integration.extra_features.simple_package", Object.class) + .verify(); } @Test public void mentionSimple_whenTestingClass_givenNothingSpecial() { ExpectedException - .when(() -> EqualsVerifier.forClass(SimplePoint.class).verify()) - .assertFailure() - .assertMessageContains("or use EqualsVerifier.simple()"); + .when(() -> EqualsVerifier.forClass(SimplePoint.class).verify()) + .assertFailure() + .assertMessageContains("or use EqualsVerifier.simple()"); } @Test public void mentionSimple_whenTestingClassesRecursively_givenNothingSpecial() { ExpectedException - .when(() -> - EqualsVerifier - .forPackage( - "nl.jqno.equalsverifier.integration.extra_features.simple_package", - true - ) - .verify() - ) - .assertFailure() - .assertMessageContains("or use EqualsVerifier.simple()"); + .when( + () -> EqualsVerifier + .forPackage("nl.jqno.equalsverifier.integration.extra_features.simple_package", true) + .verify()) + .assertFailure() + .assertMessageContains("or use EqualsVerifier.simple()"); } @Test public void mentionSimple_whenTestingClassesThatMustExtendSomething_givenNothingSpecial() { ExpectedException - .when(() -> - EqualsVerifier - .forPackage( - "nl.jqno.equalsverifier.integration.extra_features.simple_package", - Object.class - ) - .verify() - ) - .assertFailure() - .assertMessageContains("or use EqualsVerifier.simple()"); + .when( + () -> EqualsVerifier + .forPackage( + "nl.jqno.equalsverifier.integration.extra_features.simple_package", + Object.class) + .verify()) + .assertFailure() + .assertMessageContains("or use EqualsVerifier.simple()"); } @Test public void mentionSimple_whenTestingClass_givenSuppressWarningStrictInheritance() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(SimplePoint.class) - .suppress(Warning.STRICT_INHERITANCE) - .verify() - ) - .assertFailure() - .assertMessageContains("or use EqualsVerifier.simple()"); + .when(() -> EqualsVerifier.forClass(SimplePoint.class).suppress(Warning.STRICT_INHERITANCE).verify()) + .assertFailure() + .assertMessageContains("or use EqualsVerifier.simple()"); } @Test public void fail_whenTestingClassesRecursively_whenPackageHasNoClasses() { ExpectedException - .when(() -> - EqualsVerifier - .simple() - .forPackage("nl.jqno.equalsverifier.doesnotexist", true) - .verify() - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "nl.jqno.equalsverifier.doesnotexist", - "doesn't contain any (non-Test) types" - ); + .when(() -> EqualsVerifier.simple().forPackage("nl.jqno.equalsverifier.doesnotexist", true).verify()) + .assertThrows(IllegalStateException.class) + .assertMessageContains("nl.jqno.equalsverifier.doesnotexist", "doesn't contain any (non-Test) types"); } @Test public void fail_whenTestingClassesThatMustExtendSomething_whenPackageHasNoClasses() { ExpectedException - .when(() -> - EqualsVerifier - .simple() - .forPackage("nl.jqno.equalsverifier.doesnotexist", Object.class) - .verify() - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "nl.jqno.equalsverifier.doesnotexist", - "doesn't contain any (non-Test) types" - ); + .when( + () -> EqualsVerifier + .simple() + .forPackage("nl.jqno.equalsverifier.doesnotexist", Object.class) + .verify()) + .assertThrows(IllegalStateException.class) + .assertMessageContains("nl.jqno.equalsverifier.doesnotexist", "doesn't contain any (non-Test) types"); } public static class SimplePoint { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/VersionedEntityTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/VersionedEntityTest.java index 0140e2cf8..5befe5363 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/VersionedEntityTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/VersionedEntityTest.java @@ -4,6 +4,7 @@ import java.util.Objects; import java.util.UUID; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; @@ -18,137 +19,128 @@ public class VersionedEntityTest { @Test public void fail_whenInstanceWithAZeroIdDoesNotEqualItself() { ExpectedException - .when(() -> EqualsVerifier.forClass(OtherwiseStatelessVersionedEntity.class).verify()) - .assertFailure() - .assertMessageContains( - "entity does not equal an identical copy of itself", - Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY.toString() - ); + .when(() -> EqualsVerifier.forClass(OtherwiseStatelessVersionedEntity.class).verify()) + .assertFailure() + .assertMessageContains( + "entity does not equal an identical copy of itself", + Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY.toString()); } @Test public void fail_whenInstanceWithANonzeroIdEqualsItself_givenIdenticalCopyWarningIsSuppressed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(OtherwiseStatelessVersionedEntity.class) - .suppress(Warning.IDENTICAL_COPY) - .verify() - ) - .assertFailure() - .assertMessageContains("Unnecessary suppression", Warning.IDENTICAL_COPY.toString()); + .when( + () -> EqualsVerifier + .forClass(OtherwiseStatelessVersionedEntity.class) + .suppress(Warning.IDENTICAL_COPY) + .verify()) + .assertFailure() + .assertMessageContains("Unnecessary suppression", Warning.IDENTICAL_COPY.toString()); } @Test public void succeed_whenInstanceWithAZeroIdDoesNotEqualItselfAndInstanceWithANonzeroIdDoes_givenVersionedEntityWarningIsSuppressed() { EqualsVerifier - .forClass(OtherwiseStatelessVersionedEntity.class) - .suppress(Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY, Warning.SURROGATE_KEY) - .verify(); + .forClass(OtherwiseStatelessVersionedEntity.class) + .suppress(Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY, Warning.SURROGATE_KEY) + .verify(); } @Test public void fail_whenInstanceWithAZeroIdDoesNotEqualItself_givenAVersionedEntityWithState() { ExpectedException - .when(() -> EqualsVerifier.forClass(LongIdStringFieldVersionedEntity.class).verify()) - .assertFailure() - .assertMessageContains( - "entity does not equal an identical copy of itself", - Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY.toString() - ); + .when(() -> EqualsVerifier.forClass(LongIdStringFieldVersionedEntity.class).verify()) + .assertFailure() + .assertMessageContains( + "entity does not equal an identical copy of itself", + Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY.toString()); } @Test public void fail_whenInstanceWithANonzeroIdEqualsItself_givenAVersionedEntityWithStateAndIdenticalCopyWarningIsSuppressed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(LongIdStringFieldVersionedEntity.class) - .suppress(Warning.IDENTICAL_COPY) - .verify() - ) - .assertFailure() - .assertMessageContains("Unnecessary suppression", Warning.IDENTICAL_COPY.toString()); + .when( + () -> EqualsVerifier + .forClass(LongIdStringFieldVersionedEntity.class) + .suppress(Warning.IDENTICAL_COPY) + .verify()) + .assertFailure() + .assertMessageContains("Unnecessary suppression", Warning.IDENTICAL_COPY.toString()); } @Test public void succeed_whenInstanceWithAZeroIdDoesNotEqualItselfAndInstanceWithANonzeroIdDoes_givenAVersionedEntityWithStateAndVersionedEntityWarningIsSuppressed() { EqualsVerifier - .forClass(LongIdStringFieldVersionedEntity.class) - .suppress(Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY, Warning.SURROGATE_KEY) - .verify(); + .forClass(LongIdStringFieldVersionedEntity.class) + .suppress(Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY, Warning.SURROGATE_KEY) + .verify(); } @Test public void fail_whenInstanceWithANullIdDoesNotEqualItself_givenAVersionedEntityWithState() { ExpectedException - .when(() -> EqualsVerifier.forClass(UuidIdStringFieldVersionedEntity.class).verify()) - .assertFailure() - .assertMessageContains( - "entity does not equal an identical copy of itself", - Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY.toString() - ); + .when(() -> EqualsVerifier.forClass(UuidIdStringFieldVersionedEntity.class).verify()) + .assertFailure() + .assertMessageContains( + "entity does not equal an identical copy of itself", + Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY.toString()); } @Test public void fail_whenInstanceWithANonnullIdEqualsItself_givenAVersionedEntityWithStateAndIdenticalCopyWarningIsSuppressed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(UuidIdStringFieldVersionedEntity.class) - .suppress(Warning.IDENTICAL_COPY) - .verify() - ) - .assertFailure() - .assertMessageContains("Unnecessary suppression", Warning.IDENTICAL_COPY.toString()); + .when( + () -> EqualsVerifier + .forClass(UuidIdStringFieldVersionedEntity.class) + .suppress(Warning.IDENTICAL_COPY) + .verify()) + .assertFailure() + .assertMessageContains("Unnecessary suppression", Warning.IDENTICAL_COPY.toString()); } @Test public void succeed_whenInstanceWithANullIdDoesNotEqualItselfAndInstanceWithANonnullIdDoes_givenAVersionedEntityWithStateAndVersionedEntityWarningIsSuppressed() { EqualsVerifier - .forClass(UuidIdStringFieldVersionedEntity.class) - .suppress(Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY, Warning.SURROGATE_KEY) - .verify(); + .forClass(UuidIdStringFieldVersionedEntity.class) + .suppress(Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY, Warning.SURROGATE_KEY) + .verify(); } @Test public void fail_whenInstanceWithAZeroIdCanEqualItselfAndInstanceWithANonzeroIdAlso_givenAVersionedEntityWithState() { ExpectedException - .when(() -> EqualsVerifier.forClass(WeakStringVersionedEntity.class).verify()) - .assertFailure() - .assertMessageContains("Significant fields"); + .when(() -> EqualsVerifier.forClass(WeakStringVersionedEntity.class).verify()) + .assertFailure() + .assertMessageContains("Significant fields"); } @Test public void succeed_whenInstanceWithAZeroIdCanEqualItselfAndInstanceWithANonzeroIdAlso_givenAVersionedEntityWithStateAndVersionedEntityWarningIsSuppressed() { EqualsVerifier - .forClass(WeakStringVersionedEntity.class) - .suppress(Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY, Warning.SURROGATE_KEY) - .verify(); + .forClass(WeakStringVersionedEntity.class) + .suppress(Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY, Warning.SURROGATE_KEY) + .verify(); } @Test public void succeed_whenInstanceWithAZeroIdCanEqualItselfAndInstanceWithANonzeroIdAlso_givenAVersionedEntityWithStateAndAllFieldsWarningIsSuppressed() { - EqualsVerifier - .forClass(WeakStringVersionedEntity.class) - .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) - .verify(); + EqualsVerifier.forClass(WeakStringVersionedEntity.class).suppress(Warning.ALL_FIELDS_SHOULD_BE_USED).verify(); } @Test public void succeed_whenInstanceWithANullableIdDoesNullCheck_givenAVersionedEntityWithStateAndVersionedEntityWarningIsSuppressed() { EqualsVerifier - .forClass(NullCheckStringVersionedEntity.class) - .suppress(Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY, Warning.SURROGATE_KEY) - .verify(); + .forClass(NullCheckStringVersionedEntity.class) + .suppress(Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY, Warning.SURROGATE_KEY) + .verify(); } @Test public void succeed_whenEntityWithABusinessKey_givenAVersionedEntityWithStateAndVersionedEntityWarningIsSuppressed() { EqualsVerifier - .forClass(BusinessKeyStringVersionedEntity.class) - .suppress(Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY) - .verify(); + .forClass(BusinessKeyStringVersionedEntity.class) + .suppress(Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY) + .verify(); } @Test @@ -159,22 +151,21 @@ public void succeed_whenTheParentOfTheVersionedEntityIsCheckedForSanity() { @Test public void fail_whenAnExceptionIsThrownInADifficultToReachPartOfTheSubclassOfAVersionedEntity() { ExpectedException - .when(() -> EqualsVerifier.forClass(NonReflexiveCanEqualVersionedEntity.class).verify()) - .assertFailure() - .assertMessageContains("catch me if you can"); + .when(() -> EqualsVerifier.forClass(NonReflexiveCanEqualVersionedEntity.class).verify()) + .assertFailure() + .assertMessageContains("catch me if you can"); } @Test public void fail_whenTheExceptionIsThrownInADifficultToReachPartOfTheSubclassOfAVersionedEntity_givenVersionedEntityWarningIsSuppressed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(NonReflexiveCanEqualVersionedEntity.class) - .suppress(Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY) - .verify() - ) - .assertFailure() - .assertMessageContains("catch me if you can"); + .when( + () -> EqualsVerifier + .forClass(NonReflexiveCanEqualVersionedEntity.class) + .suppress(Warning.IDENTICAL_COPY_FOR_VERSIONED_ENTITY) + .verify()) + .assertFailure() + .assertMessageContains("catch me if you can"); } @Entity @@ -374,7 +365,8 @@ public final boolean equals(Object obj) { CanEqualVersionedEntity other = (CanEqualVersionedEntity) obj; if (id != null) { return id.equals(other.id); - } else if (other.id == null) { + } + else if (other.id == null) { return other.canEqual(this); } return false; diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/WarningsMixTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/WarningsMixTest.java index 6b53d838a..36d8414f8 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/WarningsMixTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/WarningsMixTest.java @@ -12,127 +12,109 @@ public class WarningsMixTest { @Test public void fail_whenFieldsAreNonfinalAndClassIsNonfinal_givenOnlyStrictInheritanceWarningIsSuppressed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(MutablePoint.class) - .suppress(Warning.STRICT_INHERITANCE) - .verify() - ) - .assertFailure() - .assertMessageContains("Mutability:"); + .when(() -> EqualsVerifier.forClass(MutablePoint.class).suppress(Warning.STRICT_INHERITANCE).verify()) + .assertFailure() + .assertMessageContains("Mutability:"); } @Test public void fail_whenFieldsAreNonFinalAndClassIsNonFinal_givenOnlyNonfinalFieldsWarningIsSuppressed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(MutablePoint.class) - .suppress(Warning.NONFINAL_FIELDS) - .verify() - ) - .assertFailure() - .assertMessageContains("Subclass:"); + .when(() -> EqualsVerifier.forClass(MutablePoint.class).suppress(Warning.NONFINAL_FIELDS).verify()) + .assertFailure() + .assertMessageContains("Subclass:"); } @Test public void succeed_whenFieldsAreNonfinalAndClassIsNonfinal_givenBothStrictInheritanceAndNonfinalFieldsWarningsAreSuppressed() { EqualsVerifier - .forClass(MutablePoint.class) - .suppress(Warning.STRICT_INHERITANCE, Warning.NONFINAL_FIELDS) - .verify(); + .forClass(MutablePoint.class) + .suppress(Warning.STRICT_INHERITANCE, Warning.NONFINAL_FIELDS) + .verify(); } @Test public void fail_whenClassIsNonfinalAndEqualsDoesNotCheckNull_givenOnlyStrictInheritanceWarningIsSuppressed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(NeverNullColorContainer.class) - .suppress(Warning.STRICT_INHERITANCE) - .verify() - ) - .assertFailure() - .assertCause(NullPointerException.class) - .assertMessageContains("Non-nullity:"); + .when( + () -> EqualsVerifier + .forClass(NeverNullColorContainer.class) + .suppress(Warning.STRICT_INHERITANCE) + .verify()) + .assertFailure() + .assertCause(NullPointerException.class) + .assertMessageContains("Non-nullity:"); } @Test public void fail_whenClassIsNonfinalAndEqualsDoesNotCheckNull_givenOnlyNullFieldsWarningIsSuppressed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(NeverNullColorContainer.class) - .suppress(Warning.NULL_FIELDS) - .verify() - ) - .assertFailure() - .assertMessageContains("Subclass:"); + .when( + () -> EqualsVerifier.forClass(NeverNullColorContainer.class).suppress(Warning.NULL_FIELDS).verify()) + .assertFailure() + .assertMessageContains("Subclass:"); } @Test public void succeed_whenClassIsNonfinalAndEqualsDoesNotCheckNull_givenBothStrictInheritanceAndNullFieldsWarningsAreSuppressed() { EqualsVerifier - .forClass(NeverNullColorContainer.class) - .suppress(Warning.STRICT_INHERITANCE, Warning.NULL_FIELDS) - .verify(); + .forClass(NeverNullColorContainer.class) + .suppress(Warning.STRICT_INHERITANCE, Warning.NULL_FIELDS) + .verify(); } @Test public void succeed_whenWarningsAreSuppressedSeparately_givenBothWarningsNeedToBeSuppressed() { EqualsVerifier - .forClass(NeverNullColorContainer.class) - .suppress(Warning.STRICT_INHERITANCE) - .suppress(Warning.NULL_FIELDS) - .verify(); + .forClass(NeverNullColorContainer.class) + .suppress(Warning.STRICT_INHERITANCE) + .suppress(Warning.NULL_FIELDS) + .verify(); } @Test public void fail_whenClassIsNonfinalAndFieldsAreNonfinalAndEqualsDoesNotCheckNull_givenOnlyStrictInheritanceAndNullFieldsWarningsAreSuppressed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(NeverNullAndMutableColorContainer.class) - .suppress(Warning.STRICT_INHERITANCE, Warning.NULL_FIELDS) - .verify() - ) - .assertFailure() - .assertMessageContains("Mutability:"); + .when( + () -> EqualsVerifier + .forClass(NeverNullAndMutableColorContainer.class) + .suppress(Warning.STRICT_INHERITANCE, Warning.NULL_FIELDS) + .verify()) + .assertFailure() + .assertMessageContains("Mutability:"); } @Test public void fail_whenClassAndFieldsAreNonfinalAndEqualsDoesNotCheckNull_givenOnlyStrictInheritanceAndNonfinalFieldsWarningsAreSuppressed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(NeverNullAndMutableColorContainer.class) - .suppress(Warning.STRICT_INHERITANCE, Warning.NONFINAL_FIELDS) - .verify() - ) - .assertFailure() - .assertCause(NullPointerException.class) - .assertMessageContains("Non-nullity:"); + .when( + () -> EqualsVerifier + .forClass(NeverNullAndMutableColorContainer.class) + .suppress(Warning.STRICT_INHERITANCE, Warning.NONFINAL_FIELDS) + .verify()) + .assertFailure() + .assertCause(NullPointerException.class) + .assertMessageContains("Non-nullity:"); } @Test public void fail_whenClassIsNonfinalAndFieldsAreNonfinalAndEqualsDoesNotCheckNull_givenOnlyNonfinalFieldsAndNullFieldsWarningsAreSuppressed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(NeverNullAndMutableColorContainer.class) - .suppress(Warning.NONFINAL_FIELDS, Warning.NULL_FIELDS) - .verify() - ) - .assertFailure() - .assertMessageContains("Subclass:"); + .when( + () -> EqualsVerifier + .forClass(NeverNullAndMutableColorContainer.class) + .suppress(Warning.NONFINAL_FIELDS, Warning.NULL_FIELDS) + .verify()) + .assertFailure() + .assertMessageContains("Subclass:"); } @Test public void succeed_whenClassIsNonfinalAndFieldsAreNonfinalAndEqualsDoesNotCheckNull_givenAllNecessaryWarningsAreSuppressed() { EqualsVerifier - .forClass(NeverNullAndMutableColorContainer.class) - .suppress(Warning.STRICT_INHERITANCE, Warning.NULL_FIELDS, Warning.NONFINAL_FIELDS) - .verify(); + .forClass(NeverNullAndMutableColorContainer.class) + .suppress(Warning.STRICT_INHERITANCE, Warning.NULL_FIELDS, Warning.NONFINAL_FIELDS) + .verify(); } static class NeverNullColorContainer { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/nonnull/findbugs1x/custom/NonnullFindbugs1xWithCheckForNullOnPackage.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/nonnull/findbugs1x/custom/NonnullFindbugs1xWithCheckForNullOnPackage.java index 299bf1b2e..4438c3f8f 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/nonnull/findbugs1x/custom/NonnullFindbugs1xWithCheckForNullOnPackage.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/nonnull/findbugs1x/custom/NonnullFindbugs1xWithCheckForNullOnPackage.java @@ -19,8 +19,7 @@ public boolean equals(Object obj) { if (!(obj instanceof NonnullFindbugs1xWithCheckForNullOnPackage)) { return false; } - NonnullFindbugs1xWithCheckForNullOnPackage other = - (NonnullFindbugs1xWithCheckForNullOnPackage) obj; + NonnullFindbugs1xWithCheckForNullOnPackage other = (NonnullFindbugs1xWithCheckForNullOnPackage) obj; return o.equals(other.o) && p.equals(other.p); } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/nonnull/findbugs1x/javax/package-info.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/nonnull/findbugs1x/javax/package-info.java index 2ee53e96a..4770a66cc 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/nonnull/findbugs1x/javax/package-info.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/nonnull/findbugs1x/javax/package-info.java @@ -5,4 +5,5 @@ package nl.jqno.equalsverifier.integration.extra_features.nonnull.findbugs1x.javax; import javax.annotation.Nonnull; + import nl.jqno.equalsverifier.testhelpers.annotations.edu.umd.cs.findbugs.annotations.DefaultAnnotation; diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/nonnull/jsr305/custom/package-info.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/nonnull/jsr305/custom/package-info.java index 655840269..c8868a658 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/nonnull/jsr305/custom/package-info.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/nonnull/jsr305/custom/package-info.java @@ -1,6 +1,5 @@ /** - * Applies a custom Nonnull annotation to the whole package using JSR305's default annotation - * system. + * Applies a custom Nonnull annotation to the whole package using JSR305's default annotation system. */ @DefaultNonnullCustom package nl.jqno.equalsverifier.integration.extra_features.nonnull.jsr305.custom; diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/nonnull/jsr305/inapplicable/package-info.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/nonnull/jsr305/inapplicable/package-info.java index 0da9513a0..4fca7f8e0 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/nonnull/jsr305/inapplicable/package-info.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/nonnull/jsr305/inapplicable/package-info.java @@ -1,6 +1,6 @@ /** - * Applies a Nonnull annotation to the whole package using JSR305's default annotation system, but - * in a way that makes Nonnull inapplicable. + * Applies a Nonnull annotation to the whole package using JSR305's default annotation system, but in a way that makes + * Nonnull inapplicable. */ @DefaultNonnullInapplicable package nl.jqno.equalsverifier.integration.extra_features.nonnull.jsr305.inapplicable; diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/simple_package/SimplePoint.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/simple_package/SimplePoint.java index ca5ce9152..4a58dd884 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/simple_package/SimplePoint.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/simple_package/SimplePoint.java @@ -1,6 +1,7 @@ package nl.jqno.equalsverifier.integration.extra_features.simple_package; import java.util.Objects; + import nl.jqno.equalsverifier.testhelpers.types.Color; public class SimplePoint { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/simple_package/subpackage/SimplePoint.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/simple_package/subpackage/SimplePoint.java index 7430f5a9b..5e38dd0c8 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/simple_package/subpackage/SimplePoint.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/extra_features/simple_package/subpackage/SimplePoint.java @@ -1,6 +1,7 @@ package nl.jqno.equalsverifier.integration.extra_features.simple_package.subpackage; import java.util.Objects; + import nl.jqno.equalsverifier.testhelpers.types.Color; public class SimplePoint { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/inheritance/AbstractHierarchyTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/inheritance/AbstractHierarchyTest.java index 3e3d890fc..8db2941b1 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/inheritance/AbstractHierarchyTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/inheritance/AbstractHierarchyTest.java @@ -18,51 +18,46 @@ public void succeed_whenEqualsAndHashCodeAreFinal_givenClassIsAbstract() { @Test public void succeed_whenAnImplementingClassWithCorrectlyImplementedEquals_givenClassIsAbstract() { EqualsVerifier - .forClass(AbstractRedefinablePoint.class) - .withRedefinedSubclass(FinalRedefinedPoint.class) - .verify(); + .forClass(AbstractRedefinablePoint.class) + .withRedefinedSubclass(FinalRedefinedPoint.class) + .verify(); } @Test public void fail_whenEqualsThrowsNull_givenClassIsAbstract() { ExpectedException - .when(() -> EqualsVerifier.forClass(NullThrowingColorContainer.class).verify()) - .assertFailure() - .assertCause(NullPointerException.class) - .assertMessageContains("Non-nullity: equals throws NullPointerException"); + .when(() -> EqualsVerifier.forClass(NullThrowingColorContainer.class).verify()) + .assertFailure() + .assertCause(NullPointerException.class) + .assertMessageContains("Non-nullity: equals throws NullPointerException"); } @Test public void succeed_whenEqualsThrowsNull_givenClassIsAbstractAndWarningIsSuppressed() { - EqualsVerifier - .forClass(NullThrowingColorContainer.class) - .suppress(Warning.NULL_FIELDS) - .verify(); + EqualsVerifier.forClass(NullThrowingColorContainer.class).suppress(Warning.NULL_FIELDS).verify(); } @Test public void fail_whenAbstractImplementationThrowsNpe() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(NullThrowingLazyObjectContainer.class) - .suppress(Warning.NONFINAL_FIELDS) - .withIgnoredFields("objectFactory") - .verify() - ) - .assertFailure() - .assertMessageContains( - "Abstract delegation: equals throws AbstractMethodError when field object is null" - ); + .when( + () -> EqualsVerifier + .forClass(NullThrowingLazyObjectContainer.class) + .suppress(Warning.NONFINAL_FIELDS) + .withIgnoredFields("objectFactory") + .verify()) + .assertFailure() + .assertMessageContains( + "Abstract delegation: equals throws AbstractMethodError when field object is null"); } @Test public void succeed_whenAbstractImplementationThrowsNpe_givenWarningIsSuppressed() { EqualsVerifier - .forClass(NullThrowingLazyObjectContainer.class) - .suppress(Warning.NULL_FIELDS, Warning.NONFINAL_FIELDS) - .withIgnoredFields("objectFactory") - .verify(); + .forClass(NullThrowingLazyObjectContainer.class) + .suppress(Warning.NULL_FIELDS, Warning.NONFINAL_FIELDS) + .withIgnoredFields("objectFactory") + .verify(); } abstract static class AbstractFinalMethodsPoint { @@ -206,9 +201,7 @@ static final class NullThrowingLazyObjectContainer extends AbstractLazyObjectCon private final SupplierThatDoesntHaveAPrefab objectFactory; - protected NullThrowingLazyObjectContainer( - SupplierThatDoesntHaveAPrefab flourFactory - ) { + protected NullThrowingLazyObjectContainer(SupplierThatDoesntHaveAPrefab flourFactory) { this.objectFactory = flourFactory; } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/inheritance/FinalityTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/inheritance/FinalityTest.java index e74a186e5..86bbb71df 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/inheritance/FinalityTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/inheritance/FinalityTest.java @@ -11,10 +11,10 @@ public class FinalityTest { private static final String BOTH_FINAL_OR_NONFINAL = - "Finality: equals and hashCode must both be final or both be non-final"; + "Finality: equals and hashCode must both be final or both be non-final"; private static final String SUBCLASS = "Subclass"; private static final String SUPPLY_AN_INSTANCE = - "Make your class or your %s method final, or supply an instance of a redefined subclass using withRedefinedSubclass"; + "Make your class or your %s method final, or supply an instance of a redefined subclass using withRedefinedSubclass"; @Test public void fail_whenEqualsIsFinalButHashCodeIsNonFinal() { @@ -24,23 +24,22 @@ public void fail_whenEqualsIsFinalButHashCodeIsNonFinal() { @Test public void fail_whenEqualsIsNotFinal_givenAClassThatIsNotFinal() { ExpectedException - .when(() -> EqualsVerifier.forClass(Point.class).verify()) - .assertFailure() - .assertMessageContains( - SUBCLASS, - "equals is not final", - String.format(SUPPLY_AN_INSTANCE, "equals"), - "if equals cannot be final" - ); + .when(() -> EqualsVerifier.forClass(Point.class).verify()) + .assertFailure() + .assertMessageContains( + SUBCLASS, + "equals is not final", + String.format(SUPPLY_AN_INSTANCE, "equals"), + "if equals cannot be final"); } @Test public void succeed_whenEqualsIsFinalButHashCodeIsNonFinal_givenWarningIsSuppressed() { EqualsVerifier - .forClass(FinalEqualsNonFinalHashCode.class) - .usingGetClass() - .suppress(Warning.STRICT_INHERITANCE) - .verify(); + .forClass(FinalEqualsNonFinalHashCode.class) + .usingGetClass() + .suppress(Warning.STRICT_INHERITANCE) + .verify(); } @Test @@ -56,38 +55,34 @@ public void fail_whenEqualsIsNonFinalButHashCodeIsFinal() { @Test public void fail_whenHashCodeIsNotFinal_givenAClassThatIsNotFinalAndAnEqualsMethodThatIsFinal() { ExpectedException - .when(() -> EqualsVerifier.forClass(FinalEqualsPoint.class).verify()) - .assertFailure() - .assertMessageContains( - SUBCLASS, - "hashCode is not final", - String.format(SUPPLY_AN_INSTANCE, "hashCode"), - "if hashCode cannot be final" - ); + .when(() -> EqualsVerifier.forClass(FinalEqualsPoint.class).verify()) + .assertFailure() + .assertMessageContains( + SUBCLASS, + "hashCode is not final", + String.format(SUPPLY_AN_INSTANCE, "hashCode"), + "if hashCode cannot be final"); } @Test public void succeed_whenEqualsIsNonFinalButHashCodeIsFinal_givenWarningsAreSuppressed() { EqualsVerifier - .forClass(NonFinalEqualsFinalHashCode.class) - .usingGetClass() - .suppress(Warning.STRICT_INHERITANCE) - .verify(); + .forClass(NonFinalEqualsFinalHashCode.class) + .usingGetClass() + .suppress(Warning.STRICT_INHERITANCE) + .verify(); } @Test public void succeed_whenHashCodeIsNotFinal_givenAClassThatIsNotFinalAndAnEqualsMethodThatIsFinalAndWarningIsSuppressed() { - EqualsVerifier - .forClass(FinalEqualsPoint.class) - .suppress(Warning.STRICT_INHERITANCE) - .verify(); + EqualsVerifier.forClass(FinalEqualsPoint.class).suppress(Warning.STRICT_INHERITANCE).verify(); } private void check(Class type) { ExpectedException - .when(() -> EqualsVerifier.forClass(type).usingGetClass().verify()) - .assertFailure() - .assertMessageContains(BOTH_FINAL_OR_NONFINAL); + .when(() -> EqualsVerifier.forClass(type).usingGetClass().verify()) + .assertFailure() + .assertMessageContains(BOTH_FINAL_OR_NONFINAL); } static class FinalEqualsNonFinalHashCode { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/inheritance/SubclassTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/inheritance/SubclassTest.java index 05d2462c7..c12ef91a5 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/inheritance/SubclassTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/inheritance/SubclassTest.java @@ -11,10 +11,12 @@ /** * Tests, among other things, the following approaches to inheritance with added fields: * - *

1. "blindly equals", as described by Tal Cohen in Dr. Dobb's Journal, May 2002. See also + *

+ * 1. "blindly equals", as described by Tal Cohen in Dr. Dobb's Journal, May 2002. See also * http://www.ddj.com/java/184405053 and http://tal.forum2.org/equals * - *

2. "can equal", as described by Odersky, Spoon and Venners in Programming in Scala. + *

+ * 2. "can equal", as described by Odersky, Spoon and Venners in Programming in Scala. */ public class SubclassTest { @@ -26,40 +28,34 @@ public void succeed_whenClassIsFinal() { @Test public void fail_whenClassIsNotEqualToATrivialSubclassWithEqualFields() { ExpectedException - .when(() -> EqualsVerifier.forClass(LiskovSubstitutionPrincipleBroken.class).verify()) - .assertFailure() - .assertMessageContains( - "Subclass", - "object is not equal to an instance of a trivial subclass with equal fields", - "Maybe you forgot to add usingGetClass()", - "consider making the class final" - ); + .when(() -> EqualsVerifier.forClass(LiskovSubstitutionPrincipleBroken.class).verify()) + .assertFailure() + .assertMessageContains( + "Subclass", + "object is not equal to an instance of a trivial subclass with equal fields", + "Maybe you forgot to add usingGetClass()", + "consider making the class final"); } @Test public void fail_whenEqualsIsOverridableAndBlindlyEqualsIsPresent() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(BlindlyEqualsPoint.class) - .withRedefinedSubclass(EqualSubclassForBlindlyEqualsPoint.class) - .verify() - ) - .assertFailure() - .assertMessageContains( - "Subclass", - BlindlyEqualsPoint.class.getSimpleName(), - "equals subclass instance", - EqualSubclassForBlindlyEqualsPoint.class.getSimpleName() - ); + .when( + () -> EqualsVerifier + .forClass(BlindlyEqualsPoint.class) + .withRedefinedSubclass(EqualSubclassForBlindlyEqualsPoint.class) + .verify()) + .assertFailure() + .assertMessageContains( + "Subclass", + BlindlyEqualsPoint.class.getSimpleName(), + "equals subclass instance", + EqualSubclassForBlindlyEqualsPoint.class.getSimpleName()); } @Test public void succeed_whenEqualsIsOverridableAndBlindlyEqualsIsPresent_givenACorrectSubclass() { - EqualsVerifier - .forClass(BlindlyEqualsPoint.class) - .withRedefinedSubclass(BlindlyEqualsColorPoint.class) - .verify(); + EqualsVerifier.forClass(BlindlyEqualsPoint.class).withRedefinedSubclass(BlindlyEqualsColorPoint.class).verify(); } @Test @@ -70,27 +66,22 @@ public void succeed_whenEqualsIsOverriddenTwiceThroughBlindlyEquals_givenWithRed @Test public void fail_whenEqualsIsOverridableAndCanEqualIsPresent() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(CanEqualPoint.class) - .withRedefinedSubclass(EqualSubclassForCanEqualPoint.class) - .verify() - ) - .assertFailure() - .assertMessageContains( - "Subclass", - CanEqualPoint.class.getSimpleName(), - "equals subclass instance", - EqualSubclassForCanEqualPoint.class.getSimpleName() - ); + .when( + () -> EqualsVerifier + .forClass(CanEqualPoint.class) + .withRedefinedSubclass(EqualSubclassForCanEqualPoint.class) + .verify()) + .assertFailure() + .assertMessageContains( + "Subclass", + CanEqualPoint.class.getSimpleName(), + "equals subclass instance", + EqualSubclassForCanEqualPoint.class.getSimpleName()); } @Test public void succeed_whenEqualsIsOverridableAndCanEqualIsPresent_givenACorrectSubclass() { - EqualsVerifier - .forClass(CanEqualPoint.class) - .withRedefinedSubclass(CanEqualColorPoint.class) - .verify(); + EqualsVerifier.forClass(CanEqualPoint.class).withRedefinedSubclass(CanEqualColorPoint.class).verify(); } @Test @@ -101,63 +92,51 @@ public void succeed_whenEqualsIsOverridenTwiceThroughCanEqual_givenWithRedefined @Test public void fail_whenWithRedefinedEqualsIsUsed_givenEqualsAndHashCodeAreFinal() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(FinalEqualsAndHashCode.class) - .withRedefinedSubclass(RedeFinalSubPoint.class) - .verify() - ) - .assertFailure() - .assertMessageContains( - "Subclass", - FinalEqualsAndHashCode.class.getSimpleName(), - "has a final equals method", - "No need to supply a redefined subclass" - ); + .when( + () -> EqualsVerifier + .forClass(FinalEqualsAndHashCode.class) + .withRedefinedSubclass(RedeFinalSubPoint.class) + .verify()) + .assertFailure() + .assertMessageContains( + "Subclass", + FinalEqualsAndHashCode.class.getSimpleName(), + "has a final equals method", + "No need to supply a redefined subclass"); } @Test public void succeed_whenClassIsAbstract_givenACorrectImplementationOfEqualsUnderInheritanceAndARedefinedSubclass() { EqualsVerifier - .forClass(AbstractRedefinablePoint.class) - .withRedefinedSubclass(SubclassForAbstractRedefinablePoint.class) - .verify(); + .forClass(AbstractRedefinablePoint.class) + .withRedefinedSubclass(SubclassForAbstractRedefinablePoint.class) + .verify(); } @Test public void fail_whenWithRedefinedSubclassIsUsed_givenStrictInheritanceWarningIsSuppressed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(CanEqualPoint.class) - .suppress(Warning.STRICT_INHERITANCE) - .withRedefinedSubclass(EqualSubclassForCanEqualPoint.class) - .verify() - ) - .assertFailure() - .assertMessageContains( - "withRedefinedSubclass", - "weakInheritanceCheck", - "are mutually exclusive" - ); + .when( + () -> EqualsVerifier + .forClass(CanEqualPoint.class) + .suppress(Warning.STRICT_INHERITANCE) + .withRedefinedSubclass(EqualSubclassForCanEqualPoint.class) + .verify()) + .assertFailure() + .assertMessageContains("withRedefinedSubclass", "weakInheritanceCheck", "are mutually exclusive"); } @Test public void fail_whenStrictInhertianceWarningIsSuppressed_givenWithRedefinedSubclassIsUsed() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(CanEqualPoint.class) - .withRedefinedSubclass(EqualSubclassForCanEqualPoint.class) - .suppress(Warning.STRICT_INHERITANCE) - .verify() - ) - .assertFailure() - .assertMessageContains( - "withRedefinedSubclass", - "weakInheritanceCheck", - "are mutually exclusive" - ); + .when( + () -> EqualsVerifier + .forClass(CanEqualPoint.class) + .withRedefinedSubclass(EqualSubclassForCanEqualPoint.class) + .suppress(Warning.STRICT_INHERITANCE) + .verify()) + .assertFailure() + .assertMessageContains("withRedefinedSubclass", "weakInheritanceCheck", "are mutually exclusive"); } static class LiskovSubstitutionPrincipleBroken { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/inheritance/SuperclassTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/inheritance/SuperclassTest.java index 48baa70a4..e6c610c28 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/inheritance/SuperclassTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/inheritance/SuperclassTest.java @@ -3,6 +3,7 @@ import static nl.jqno.equalsverifier.internal.testhelpers.Util.defaultHashCode; import java.util.Objects; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; @@ -20,51 +21,45 @@ public class SuperclassTest { @Test public void succeed_whenSubclassRedefinesEqualsButOnlyCallsSuper_givenSuperHasRedefinedAlsoAndAllFieldsWarningIsSuppressed() { - EqualsVerifier - .forClass(ColorBlindColorPoint.class) - .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) - .verify(); + EqualsVerifier.forClass(ColorBlindColorPoint.class).suppress(Warning.ALL_FIELDS_SHOULD_BE_USED).verify(); } @Test public void fail_whenEqualsIsRedefinedSoItBreaksSymmetry_givenSuperHasRedefinedAlso() { ExpectedException - .when(() -> EqualsVerifier.forClass(SymmetryBrokenColorPoint.class).verify()) - .assertFailure() - .assertMessageContains( - "Symmetry", - SymmetryBrokenColorPoint.class.getSimpleName(), - "does not equal superclass instance", - Point.class.getSimpleName() - ); + .when(() -> EqualsVerifier.forClass(SymmetryBrokenColorPoint.class).verify()) + .assertFailure() + .assertMessageContains( + "Symmetry", + SymmetryBrokenColorPoint.class.getSimpleName(), + "does not equal superclass instance", + Point.class.getSimpleName()); } @Test public void fail_whenEqualsIsRedefinedSoItBreaksTransitivity_givenSuperHasRedefinedAlso() { ExpectedException - .when(() -> EqualsVerifier.forClass(TransitivityBrokenColorPoint.class).verify()) - .assertFailure() - .assertMessageContains( - "Transitivity", - TransitivityBrokenColorPoint.class.getSimpleName(), - "both equal superclass instance", - Point.class.getSimpleName(), - "which implies they equal each other." - ); + .when(() -> EqualsVerifier.forClass(TransitivityBrokenColorPoint.class).verify()) + .assertFailure() + .assertMessageContains( + "Transitivity", + TransitivityBrokenColorPoint.class.getSimpleName(), + "both equal superclass instance", + Point.class.getSimpleName(), + "which implies they equal each other."); } @Test public void fail_whenClassHasDifferentHashCodeThanSuper_givenEqualsIsTheSame() { ExpectedException - .when(() -> EqualsVerifier.forClass(HashCodeBrokenPoint.class).verify()) - .assertFailure() - .assertMessageContains( - "Superclass", - "hashCode for", - HashCodeBrokenPoint.class.getSimpleName(), - "should be equal to hashCode for superclass instance", - Point.class.getSimpleName() - ); + .when(() -> EqualsVerifier.forClass(HashCodeBrokenPoint.class).verify()) + .assertFailure() + .assertMessageContains( + "Superclass", + "hashCode for", + HashCodeBrokenPoint.class.getSimpleName(), + "should be equal to hashCode for superclass instance", + Point.class.getSimpleName()); } @Test @@ -77,33 +72,22 @@ public void succeed_whenSuperDoesNotRedefineEquals() { @Test public void fail_whenSuperDoesNotRedefineEquals_givenSuperOfSuperDoesRedefineEquals() { ExpectedException - .when(() -> - EqualsVerifier.forClass(BrokenCanEqualColorPointWithEmptySuper.class).verify() - ) - .assertFailure() - .assertMessageContains( - "Symmetry", - BrokenCanEqualColorPointWithEmptySuper.class.getSimpleName() - ); + .when(() -> EqualsVerifier.forClass(BrokenCanEqualColorPointWithEmptySuper.class).verify()) + .assertFailure() + .assertMessageContains("Symmetry", BrokenCanEqualColorPointWithEmptySuper.class.getSimpleName()); } @Test public void fail_whenWithRedefinedSuperclassIsUsed_givenItIsNotNeeded() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(ColorBlindColorPoint.class) - .withRedefinedSuperclass() - .verify() - ) - .assertFailure() - .assertMessageContains( - "Redefined superclass", - ColorBlindColorPoint.class.getSimpleName(), - "should not equal superclass instance", - Point.class.getSimpleName(), - "but it does" - ); + .when(() -> EqualsVerifier.forClass(ColorBlindColorPoint.class).withRedefinedSuperclass().verify()) + .assertFailure() + .assertMessageContains( + "Redefined superclass", + ColorBlindColorPoint.class.getSimpleName(), + "should not equal superclass instance", + Point.class.getSimpleName(), + "but it does"); } @Test @@ -119,13 +103,9 @@ public void succeed_whenVersionedEntityIncorrectlyImplementsCanEqual_givenIncorr @Test public void fail_whenSuperclassIsVersionedEntityAndIncorrectlyImplementsCanEqual_givenASubclassThatExploitsTheIncorrectness() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(SymmetryBrokenForNullIdWithIncorrectCanEqualSub.class) - .verify() - ) - .assertFailure() - .assertMessageContains("Symmetry", "does not equal superclass instance"); + .when(() -> EqualsVerifier.forClass(SymmetryBrokenForNullIdWithIncorrectCanEqualSub.class).verify()) + .assertFailure() + .assertMessageContains("Symmetry", "does not equal superclass instance"); } static class SymmetryBrokenColorPoint extends Point { @@ -331,11 +311,12 @@ public final boolean equals(Object obj) { return false; } SymmetryBrokenForNullIdWithIncorrectCanEqualSuper other = - (SymmetryBrokenForNullIdWithIncorrectCanEqualSuper) obj; + (SymmetryBrokenForNullIdWithIncorrectCanEqualSuper) obj; if (id != null) { return id.equals(other.id); - } else if (other.id == null) { + } + else if (other.id == null) { return other.newCanEqual(this); } return false; @@ -352,7 +333,7 @@ public final int hashCode() { } public static class SymmetryBrokenForNullIdWithIncorrectCanEqualSub - extends SymmetryBrokenForNullIdWithIncorrectCanEqualSuper { + extends SymmetryBrokenForNullIdWithIncorrectCanEqualSuper { public final String name; @@ -365,7 +346,7 @@ public SymmetryBrokenForNullIdWithIncorrectCanEqualSub(Long id, String name) { public boolean newCanEqual(SymmetryBrokenForNullIdWithIncorrectCanEqualSuper obj) { if (obj instanceof SymmetryBrokenForNullIdWithIncorrectCanEqualSub) { SymmetryBrokenForNullIdWithIncorrectCanEqualSub other = - (SymmetryBrokenForNullIdWithIncorrectCanEqualSub) obj; + (SymmetryBrokenForNullIdWithIncorrectCanEqualSub) obj; return Objects.equals(name, other.name); } return false; diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/ConfiguredEqualsVerifierMultipleTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/ConfiguredEqualsVerifierMultipleTest.java index 8600efe44..9d14e7148 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/ConfiguredEqualsVerifierMultipleTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/ConfiguredEqualsVerifierMultipleTest.java @@ -5,6 +5,7 @@ import java.util.Arrays; import java.util.List; + import nl.jqno.equalsverifier.ConfiguredEqualsVerifier; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.EqualsVerifierReport; @@ -27,19 +28,16 @@ public class ConfiguredEqualsVerifierMultipleTest { @Test public void succeed_whenCallingForPackage_givenAllClassesInPackageAreCorrect() { - EqualsVerifier - .configure() - .forPackage("nl.jqno.equalsverifier.testhelpers.packages.correct") - .verify(); + EqualsVerifier.configure().forPackage("nl.jqno.equalsverifier.testhelpers.packages.correct").verify(); } @Test public void succeed_whenEqualsVerifierUsesGetClassInsteadOfInstanceOf_givenUsingGetClassIsPreConfigured_forIterableOverload() { List reports = EqualsVerifier - .configure() - .usingGetClass() - .forClasses(Arrays.asList(GetClassPoint.class, FinalMethodsPoint.class)) - .report(); + .configure() + .usingGetClass() + .forClasses(Arrays.asList(GetClassPoint.class, FinalMethodsPoint.class)) + .report(); assertTrue(reports.get(0).isSuccessful()); assertFalse(reports.get(1).isSuccessful()); @@ -48,10 +46,10 @@ public void succeed_whenEqualsVerifierUsesGetClassInsteadOfInstanceOf_givenUsing @Test public void succeed_whenEqualsUsesGetClassInsteadOfInstanceOf_givenUsingGetClassIsPreConfigured_forVarargOverload() { List reports = EqualsVerifier - .configure() - .usingGetClass() - .forClasses(GetClassPoint.class, FinalMethodsPoint.class) - .report(); + .configure() + .usingGetClass() + .forClasses(GetClassPoint.class, FinalMethodsPoint.class) + .report(); assertTrue(reports.get(0).isSuccessful()); assertFalse(reports.get(1).isSuccessful()); @@ -60,77 +58,72 @@ public void succeed_whenEqualsUsesGetClassInsteadOfInstanceOf_givenUsingGetClass @Test public void suppressedWarningsArePassedOn() { EqualsVerifier - .configure() - .suppress(Warning.STRICT_INHERITANCE) - .forClasses(PointContainer.class, A.class) - .verify(); + .configure() + .suppress(Warning.STRICT_INHERITANCE) + .forClasses(PointContainer.class, A.class) + .verify(); } @Test public void sanity_fail_whenTypeIsRecursive() { ExpectedException - .when(() -> EqualsVerifier.forClasses(RecursiveType.class, A.class).verify()) - .assertFailure() - .assertMessageContains("Recursive datastructure"); + .when(() -> EqualsVerifier.forClasses(RecursiveType.class, A.class).verify()) + .assertFailure() + .assertMessageContains("Recursive datastructure"); } @Test public void succeed_whenTypeIsRecursive_givenPrefabValuesArePreconfigured() { EqualsVerifier - .configure() - .withPrefabValues( - RecursiveType.class, - new RecursiveType(null), - new RecursiveType(new RecursiveType(null)) - ) - .forClasses(RecursiveTypeContainer.class, A.class) - .verify(); + .configure() + .withPrefabValues( + RecursiveType.class, + new RecursiveType(null), + new RecursiveType(new RecursiveType(null))) + .forClasses(RecursiveTypeContainer.class, A.class) + .verify(); } @Test public void sanity_fail_whenSingleGenericTypeIsRecursive() { ExpectedException - .when(() -> - EqualsVerifier.forClasses(SingleGenericContainerContainer.class, A.class).verify() - ) - .assertFailure() - .assertMessageContains("Recursive datastructure"); + .when(() -> EqualsVerifier.forClasses(SingleGenericContainerContainer.class, A.class).verify()) + .assertFailure() + .assertMessageContains("Recursive datastructure"); } @Test public void succeed_whenSingleGenericTypeIsRecursive_givenGenericPrefabValuesArePreconfigured() { EqualsVerifier - .configure() - .withGenericPrefabValues(SingleGenericContainer.class, SingleGenericContainer::new) - .forClasses(SingleGenericContainerContainer.class, A.class) - .verify(); + .configure() + .withGenericPrefabValues(SingleGenericContainer.class, SingleGenericContainer::new) + .forClasses(SingleGenericContainerContainer.class, A.class) + .verify(); } @Test public void sanity_fail_whenDoubleGenericTypeIsRecursive() { ExpectedException - .when(() -> - EqualsVerifier.forClasses(DoubleGenericContainerContainer.class, A.class).verify() - ) - .assertFailure() - .assertMessageContains("Recursive datastructure"); + .when(() -> EqualsVerifier.forClasses(DoubleGenericContainerContainer.class, A.class).verify()) + .assertFailure() + .assertMessageContains("Recursive datastructure"); } @Test public void succeed_whenDoubleGenericTypeIsRecursive_givenGenericPrefabValuesArePreconfigured() { EqualsVerifier - .configure() - .withGenericPrefabValues(DoubleGenericContainer.class, DoubleGenericContainer::new) - .forClasses(DoubleGenericContainerContainer.class, A.class) - .verify(); + .configure() + .withGenericPrefabValues(DoubleGenericContainer.class, DoubleGenericContainer::new) + .forClasses(DoubleGenericContainerContainer.class, A.class) + .verify(); } @Test public void succeed_whenConfigurationIsShared() { ConfiguredEqualsVerifier ev = EqualsVerifier - .configure() - .withGenericPrefabValues(SingleGenericContainer.class, SingleGenericContainer::new) - .withGenericPrefabValues(DoubleGenericContainer.class, DoubleGenericContainer::new); + .configure() + .withGenericPrefabValues(SingleGenericContainer.class, SingleGenericContainer::new) + .withGenericPrefabValues(DoubleGenericContainer.class, DoubleGenericContainer::new); ev.forClasses(SingleGenericContainerContainer.class, A.class).verify(); ev.forClasses(DoubleGenericContainerContainer.class, A.class).verify(); @@ -138,18 +131,16 @@ public void succeed_whenConfigurationIsShared() { @Test public void individuallySuppressedWarningsAreNotAddedGlobally() { - ConfiguredEqualsVerifier ev = EqualsVerifier - .configure() - .suppress(Warning.STRICT_INHERITANCE); + ConfiguredEqualsVerifier ev = EqualsVerifier.configure().suppress(Warning.STRICT_INHERITANCE); // should succeed ev.forClasses(MutablePoint.class, A.class).suppress(Warning.NONFINAL_FIELDS).verify(); // NONFINAL_FIELDS is not added to configuration, so should fail ExpectedException - .when(() -> ev.forClasses(MutablePoint.class, A.class).verify()) - .assertFailure() - .assertMessageContains("Mutability"); + .when(() -> ev.forClasses(MutablePoint.class, A.class).verify()) + .assertFailure() + .assertMessageContains("Mutability"); } @Test @@ -158,19 +149,18 @@ public void individuallyAddedPrefabValuesAreNotAddedGlobally() { // should succeed ev - .forClasses(RecursiveTypeContainer.class, A.class) - .withPrefabValues( - RecursiveType.class, - new RecursiveType(null), - new RecursiveType(new RecursiveType(null)) - ) - .verify(); + .forClasses(RecursiveTypeContainer.class, A.class) + .withPrefabValues( + RecursiveType.class, + new RecursiveType(null), + new RecursiveType(new RecursiveType(null))) + .verify(); // PrefabValues are not added to configuration, so should fail ExpectedException - .when(() -> ev.forClasses(RecursiveTypeContainer.class, A.class).verify()) - .assertFailure() - .assertMessageContains("Recursive datastructure"); + .when(() -> ev.forClasses(RecursiveTypeContainer.class, A.class).verify()) + .assertFailure() + .assertMessageContains("Recursive datastructure"); } @Test @@ -179,31 +169,31 @@ public void individuallyAddedGenericPrefabValuesAreNotAddedGlobally() { // should succeed ev - .forClasses(SingleGenericContainerContainer.class, A.class) - .withGenericPrefabValues(SingleGenericContainer.class, SingleGenericContainer::new) - .verify(); + .forClasses(SingleGenericContainerContainer.class, A.class) + .withGenericPrefabValues(SingleGenericContainer.class, SingleGenericContainer::new) + .verify(); // PrefabValues are not added to configuration, so should fail ExpectedException - .when(() -> ev.forClasses(SingleGenericContainerContainer.class, A.class).verify()) - .assertFailure() - .assertMessageContains("Recursive datastructure"); + .when(() -> ev.forClasses(SingleGenericContainerContainer.class, A.class).verify()) + .assertFailure() + .assertMessageContains("Recursive datastructure"); } @Test public void succeed_whenFieldsAreNonfinalAndClassIsNonfinal_givenTwoWarningsAreSuppressedButInDifferentPlaces() { EqualsVerifier - .configure() - .suppress(Warning.STRICT_INHERITANCE) - .forClasses(MutablePoint.class, A.class) - .suppress(Warning.NONFINAL_FIELDS) - .verify(); + .configure() + .suppress(Warning.STRICT_INHERITANCE) + .forClasses(MutablePoint.class, A.class) + .suppress(Warning.NONFINAL_FIELDS) + .verify(); EqualsVerifier - .configure() - .suppress(Warning.NONFINAL_FIELDS) - .forClasses(MutablePoint.class, A.class) - .suppress(Warning.STRICT_INHERITANCE) - .verify(); + .configure() + .suppress(Warning.NONFINAL_FIELDS) + .forClasses(MutablePoint.class, A.class) + .suppress(Warning.STRICT_INHERITANCE) + .verify(); } } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/ConfiguredEqualsVerifierSingleTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/ConfiguredEqualsVerifierSingleTest.java index 7ace3f1ae..8c289d64f 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/ConfiguredEqualsVerifierSingleTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/ConfiguredEqualsVerifierSingleTest.java @@ -24,74 +24,69 @@ public void succeed_whenEqualsUsesGetClassInsteadOfInstanceOf_givenUsingGetClass @Test public void suppressedWarningsArePassedOn() { - EqualsVerifier - .configure() - .suppress(Warning.STRICT_INHERITANCE) - .forClass(PointContainer.class) - .verify(); + EqualsVerifier.configure().suppress(Warning.STRICT_INHERITANCE).forClass(PointContainer.class).verify(); } @Test public void sanity_fail_whenTypeIsRecursive() { ExpectedException - .when(() -> EqualsVerifier.forClass(RecursiveType.class).verify()) - .assertFailure() - .assertMessageContains("Recursive datastructure"); + .when(() -> EqualsVerifier.forClass(RecursiveType.class).verify()) + .assertFailure() + .assertMessageContains("Recursive datastructure"); } @Test public void succeed_whenTypeIsRecursive_givenPrefabValuesArePreconfigured() { EqualsVerifier - .configure() - .withPrefabValues( - RecursiveType.class, - new RecursiveType(null), - new RecursiveType(new RecursiveType(null)) - ) - .forClass(RecursiveTypeContainer.class) - .verify(); + .configure() + .withPrefabValues( + RecursiveType.class, + new RecursiveType(null), + new RecursiveType(new RecursiveType(null))) + .forClass(RecursiveTypeContainer.class) + .verify(); } @Test public void sanity_fail_whenSingleGenericTypeIsRecursive() { ExpectedException - .when(() -> EqualsVerifier.forClass(SingleGenericContainerContainer.class).verify()) - .assertFailure() - .assertMessageContains("Recursive datastructure"); + .when(() -> EqualsVerifier.forClass(SingleGenericContainerContainer.class).verify()) + .assertFailure() + .assertMessageContains("Recursive datastructure"); } @Test public void succeed_whenSingleGenericTypeIsRecursive_givenGenericPrefabValuesArePreconfigured() { EqualsVerifier - .configure() - .withGenericPrefabValues(SingleGenericContainer.class, SingleGenericContainer::new) - .forClass(SingleGenericContainerContainer.class) - .verify(); + .configure() + .withGenericPrefabValues(SingleGenericContainer.class, SingleGenericContainer::new) + .forClass(SingleGenericContainerContainer.class) + .verify(); } @Test public void sanity_fail_whenDoubleGenericTypeIsRecursive() { ExpectedException - .when(() -> EqualsVerifier.forClass(DoubleGenericContainerContainer.class).verify()) - .assertFailure() - .assertMessageContains("Recursive datastructure"); + .when(() -> EqualsVerifier.forClass(DoubleGenericContainerContainer.class).verify()) + .assertFailure() + .assertMessageContains("Recursive datastructure"); } @Test public void succeed_whenDoubleGenericTypeIsRecursive_givenGenericPrefabValuesArePreconfigured() { EqualsVerifier - .configure() - .withGenericPrefabValues(DoubleGenericContainer.class, DoubleGenericContainer::new) - .forClass(DoubleGenericContainerContainer.class) - .verify(); + .configure() + .withGenericPrefabValues(DoubleGenericContainer.class, DoubleGenericContainer::new) + .forClass(DoubleGenericContainerContainer.class) + .verify(); } @Test public void succeed_whenConfigurationIsShared() { ConfiguredEqualsVerifier ev = EqualsVerifier - .configure() - .withGenericPrefabValues(SingleGenericContainer.class, SingleGenericContainer::new) - .withGenericPrefabValues(DoubleGenericContainer.class, DoubleGenericContainer::new); + .configure() + .withGenericPrefabValues(SingleGenericContainer.class, SingleGenericContainer::new) + .withGenericPrefabValues(DoubleGenericContainer.class, DoubleGenericContainer::new); ev.forClass(SingleGenericContainerContainer.class).verify(); ev.forClass(DoubleGenericContainerContainer.class).verify(); @@ -99,18 +94,16 @@ public void succeed_whenConfigurationIsShared() { @Test public void individuallySuppressedWarningsAreNotAddedGlobally() { - ConfiguredEqualsVerifier ev = EqualsVerifier - .configure() - .suppress(Warning.STRICT_INHERITANCE); + ConfiguredEqualsVerifier ev = EqualsVerifier.configure().suppress(Warning.STRICT_INHERITANCE); // should succeed ev.forClass(MutablePoint.class).suppress(Warning.NONFINAL_FIELDS).verify(); // NONFINAL_FIELDS is not added to configuration, so should fail ExpectedException - .when(() -> ev.forClass(MutablePoint.class).verify()) - .assertFailure() - .assertMessageContains("Mutability"); + .when(() -> ev.forClass(MutablePoint.class).verify()) + .assertFailure() + .assertMessageContains("Mutability"); } @Test @@ -119,19 +112,18 @@ public void individuallyAddedPrefabValuesAreNotAddedGlobally() { // should succeed ev - .forClass(RecursiveTypeContainer.class) - .withPrefabValues( - RecursiveType.class, - new RecursiveType(null), - new RecursiveType(new RecursiveType(null)) - ) - .verify(); + .forClass(RecursiveTypeContainer.class) + .withPrefabValues( + RecursiveType.class, + new RecursiveType(null), + new RecursiveType(new RecursiveType(null))) + .verify(); // PrefabValues are not added to configuration, so should fail ExpectedException - .when(() -> ev.forClass(RecursiveTypeContainer.class).verify()) - .assertFailure() - .assertMessageContains("Recursive datastructure"); + .when(() -> ev.forClass(RecursiveTypeContainer.class).verify()) + .assertFailure() + .assertMessageContains("Recursive datastructure"); } @Test @@ -140,31 +132,31 @@ public void individuallyAddedGenericPrefabValuesAreNotAddedGlobally() { // should succeed ev - .forClass(SingleGenericContainerContainer.class) - .withGenericPrefabValues(SingleGenericContainer.class, SingleGenericContainer::new) - .verify(); + .forClass(SingleGenericContainerContainer.class) + .withGenericPrefabValues(SingleGenericContainer.class, SingleGenericContainer::new) + .verify(); // PrefabValues are not added to configuration, so should fail ExpectedException - .when(() -> ev.forClass(SingleGenericContainerContainer.class).verify()) - .assertFailure() - .assertMessageContains("Recursive datastructure"); + .when(() -> ev.forClass(SingleGenericContainerContainer.class).verify()) + .assertFailure() + .assertMessageContains("Recursive datastructure"); } @Test public void succeed_whenFieldsAreNonfinalAndClassIsNonfinal_givenTwoWarningsAreSuppressedButInDifferentPlaces() { EqualsVerifier - .configure() - .suppress(Warning.STRICT_INHERITANCE) - .forClass(MutablePoint.class) - .suppress(Warning.NONFINAL_FIELDS) - .verify(); + .configure() + .suppress(Warning.STRICT_INHERITANCE) + .forClass(MutablePoint.class) + .suppress(Warning.NONFINAL_FIELDS) + .verify(); EqualsVerifier - .configure() - .suppress(Warning.NONFINAL_FIELDS) - .forClass(MutablePoint.class) - .suppress(Warning.STRICT_INHERITANCE) - .verify(); + .configure() + .suppress(Warning.NONFINAL_FIELDS) + .forClass(MutablePoint.class) + .suppress(Warning.STRICT_INHERITANCE) + .verify(); } } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/MultipleTypeEqualsVerifierTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/MultipleTypeEqualsVerifierTest.java index f371b9d71..c36a9f685 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/MultipleTypeEqualsVerifierTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/MultipleTypeEqualsVerifierTest.java @@ -8,6 +8,7 @@ import java.util.Arrays; import java.util.List; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.EqualsVerifierReport; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; @@ -24,14 +25,10 @@ public class MultipleTypeEqualsVerifierTest { - private static final String CORRECT_PACKAGE = - "nl.jqno.equalsverifier.testhelpers.packages.correct"; - private static final String INCORRECT_PACKAGE = - "nl.jqno.equalsverifier.testhelpers.packages.twoincorrect"; - private static final String SUBCLASSES_PACKAGE = - "nl.jqno.equalsverifier.testhelpers.packages.subclasses"; - private static final String SOME_RECURSIVE_PACKAGE = - "nl.jqno.equalsverifier.testhelpers.packages.somerecursive"; + private static final String CORRECT_PACKAGE = "nl.jqno.equalsverifier.testhelpers.packages.correct"; + private static final String INCORRECT_PACKAGE = "nl.jqno.equalsverifier.testhelpers.packages.twoincorrect"; + private static final String SUBCLASSES_PACKAGE = "nl.jqno.equalsverifier.testhelpers.packages.subclasses"; + private static final String SOME_RECURSIVE_PACKAGE = "nl.jqno.equalsverifier.testhelpers.packages.somerecursive"; private static final String INCORRECT_M = INCORRECT_PACKAGE + ".IncorrectM"; private static final String INCORRECT_N = INCORRECT_PACKAGE + ".IncorrectN"; private static final String INCORRECT_O = INCORRECT_PACKAGE + ".subpackage.IncorrectO"; @@ -71,195 +68,167 @@ public void succeed_whenVerifyingAPackageWithASuperInterface_givenOneOfTheImplem @Test public void doesNotReportNonrecursive_whenPackageContainsRecursiveAndNonrecursiveClasses() { ExpectedException - .when(() -> EqualsVerifier.forPackage(SOME_RECURSIVE_PACKAGE).verify()) - .assertFailure() - .assertMessageContains("Recursive datastructure", "RecursiveA", "RecursiveB") - .assertMessageDoesNotContain("Nonrecursive"); + .when(() -> EqualsVerifier.forPackage(SOME_RECURSIVE_PACKAGE).verify()) + .assertFailure() + .assertMessageContains("Recursive datastructure", "RecursiveA", "RecursiveB") + .assertMessageDoesNotContain("Nonrecursive"); } @Test public void fail_whenVerifyingOneIncorrectClass() { ExpectedException - .when(() -> EqualsVerifier.forClasses(A.class, IncorrectM.class, C.class).verify()) - .assertFailure() - .assertMessageContains( - "EqualsVerifier found a problem in 1 class.", - "* " + INCORRECT_M, - "Subclass: equals is not final." - ); + .when(() -> EqualsVerifier.forClasses(A.class, IncorrectM.class, C.class).verify()) + .assertFailure() + .assertMessageContains( + "EqualsVerifier found a problem in 1 class.", + "* " + INCORRECT_M, + "Subclass: equals is not final."); } @Test public void fail_whenVerifyingTwoIncorrectClasses() { ExpectedException - .when(() -> - EqualsVerifier - .forClasses(A.class, IncorrectM.class, C.class, IncorrectN.class) - .verify() - ) - .assertFailure() - .assertMessageContains( - "EqualsVerifier found a problem in 2 classes.", - "* " + INCORRECT_M, - "* " + INCORRECT_N, - "Subclass: equals is not final.", - "Reflexivity: object does not equal itself:" - ); + .when(() -> EqualsVerifier.forClasses(A.class, IncorrectM.class, C.class, IncorrectN.class).verify()) + .assertFailure() + .assertMessageContains( + "EqualsVerifier found a problem in 2 classes.", + "* " + INCORRECT_M, + "* " + INCORRECT_N, + "Subclass: equals is not final.", + "Reflexivity: object does not equal itself:"); } @Test public void fail_whenVerifyingAPackageWithTwoIncorrectClasses() { ExpectedException - .when(() -> EqualsVerifier.forPackage(INCORRECT_PACKAGE).verify()) - .assertFailure() - .assertMessageContains( - "EqualsVerifier found a problem in 2 classes.", - "* " + INCORRECT_M, - "* " + INCORRECT_N, - "Subclass: equals is not final.", - "Reflexivity: object does not equal itself:" - ); + .when(() -> EqualsVerifier.forPackage(INCORRECT_PACKAGE).verify()) + .assertFailure() + .assertMessageContains( + "EqualsVerifier found a problem in 2 classes.", + "* " + INCORRECT_M, + "* " + INCORRECT_N, + "Subclass: equals is not final.", + "Reflexivity: object does not equal itself:"); } @Test public void fail_whenVerifyingAPackageRecursivelyWithFourIncorrectClasses() { ExpectedException - .when(() -> EqualsVerifier.forPackage(INCORRECT_PACKAGE, true).verify()) - .assertFailure() - .assertMessageContains( - "EqualsVerifier found a problem in 4 classes.", - "* " + INCORRECT_M, - "* " + INCORRECT_N, - "* " + INCORRECT_O, - "* " + INCORRECT_P, - "Subclass: equals is not final.", - "Reflexivity: object does not equal itself:" - ); + .when(() -> EqualsVerifier.forPackage(INCORRECT_PACKAGE, true).verify()) + .assertFailure() + .assertMessageContains( + "EqualsVerifier found a problem in 4 classes.", + "* " + INCORRECT_M, + "* " + INCORRECT_N, + "* " + INCORRECT_O, + "* " + INCORRECT_P, + "Subclass: equals is not final.", + "Reflexivity: object does not equal itself:"); } @Test public void fail_whenVerifyingAPackageWithASuperclassWithFourIncorrectClasses() { ExpectedException - .when(() -> EqualsVerifier.forPackage(INCORRECT_PACKAGE, Object.class).verify()) - .assertFailure() - .assertMessageContains( - "EqualsVerifier found a problem in 4 classes.", - "* " + INCORRECT_M, - "* " + INCORRECT_N, - "* " + INCORRECT_O, - "* " + INCORRECT_P, - "Subclass: equals is not final.", - "Reflexivity: object does not equal itself:" - ); + .when(() -> EqualsVerifier.forPackage(INCORRECT_PACKAGE, Object.class).verify()) + .assertFailure() + .assertMessageContains( + "EqualsVerifier found a problem in 4 classes.", + "* " + INCORRECT_M, + "* " + INCORRECT_N, + "* " + INCORRECT_O, + "* " + INCORRECT_P, + "Subclass: equals is not final.", + "Reflexivity: object does not equal itself:"); } @Test public void fail_whenCallingForPackage_whenPackageHasNoClasses() { ExpectedException - .when(() -> EqualsVerifier.forPackage("nl.jqno.equalsverifier.doesnotexist")) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "nl.jqno.equalsverifier.doesnotexist", - "doesn't contain any (non-Test) types" - ); + .when(() -> EqualsVerifier.forPackage("nl.jqno.equalsverifier.doesnotexist")) + .assertThrows(IllegalStateException.class) + .assertMessageContains("nl.jqno.equalsverifier.doesnotexist", "doesn't contain any (non-Test) types"); } @Test public void fail_whenCallingForPackageRecursively_whenPackageHasNoClasses() { ExpectedException - .when(() -> EqualsVerifier.forPackage("nl.jqno.equalsverifier.doesnotexist", true)) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "nl.jqno.equalsverifier.doesnotexist", - "doesn't contain any (non-Test) types" - ); + .when(() -> EqualsVerifier.forPackage("nl.jqno.equalsverifier.doesnotexist", true)) + .assertThrows(IllegalStateException.class) + .assertMessageContains("nl.jqno.equalsverifier.doesnotexist", "doesn't contain any (non-Test) types"); } @Test public void fail_whenCallingForPackageWithASuperclass_whenPackageHasNoClasses() { ExpectedException - .when(() -> - EqualsVerifier.forPackage("nl.jqno.equalsverifier.doesnotexist", Object.class) - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "nl.jqno.equalsverifier.doesnotexist", - "doesn't contain any (non-Test) types" - ); + .when(() -> EqualsVerifier.forPackage("nl.jqno.equalsverifier.doesnotexist", Object.class)) + .assertThrows(IllegalStateException.class) + .assertMessageContains("nl.jqno.equalsverifier.doesnotexist", "doesn't contain any (non-Test) types"); } @Test public void succeed_whenCallingForPackageOnAPackageContainingFailingClasses_givenFailingClassesAreExcepted() { - EqualsVerifier - .forPackage(INCORRECT_PACKAGE) - .except(IncorrectM.class, IncorrectN.class) - .verify(); + EqualsVerifier.forPackage(INCORRECT_PACKAGE).except(IncorrectM.class, IncorrectN.class).verify(); } @Test public void succeed_whenCallingForPackageRecursivelyOnAPackageContainingFailingClasses_givenFailingClassesAreExcepted() { EqualsVerifier - .forPackage(INCORRECT_PACKAGE, true) - .except(IncorrectM.class, IncorrectN.class, IncorrectO.class, IncorrectP.class) - .verify(); + .forPackage(INCORRECT_PACKAGE, true) + .except(IncorrectM.class, IncorrectN.class, IncorrectO.class, IncorrectP.class) + .verify(); } @Test public void succeed_whenCallingForPackageWithASuperclassOnAPackageContainingFailingClasses_givenFailingClassesAreExcepted() { EqualsVerifier - .forPackage(INCORRECT_PACKAGE, Object.class) - .except(IncorrectM.class, IncorrectN.class, IncorrectO.class, IncorrectP.class) - .verify(); + .forPackage(INCORRECT_PACKAGE, Object.class) + .except(IncorrectM.class, IncorrectN.class, IncorrectO.class, IncorrectP.class) + .verify(); } @Test public void fail_whenExceptingAClassThatDoesntExistInThePackage() { ExpectedException - .when(() -> EqualsVerifier.forPackage(CORRECT_PACKAGE).except(IncorrectM.class)) - .assertThrows(IllegalStateException.class) - .assertMessageContains("Unknown class(es) found", "IncorrectM"); + .when(() -> EqualsVerifier.forPackage(CORRECT_PACKAGE).except(IncorrectM.class)) + .assertThrows(IllegalStateException.class) + .assertMessageContains("Unknown class(es) found", "IncorrectM"); } @Test public void fail_whenExceptingAClassThatDoesntExistInThePackageAndSubPackages() { ExpectedException - .when(() -> EqualsVerifier.forPackage(CORRECT_PACKAGE, true).except(IncorrectM.class)) - .assertThrows(IllegalStateException.class) - .assertMessageContains("Unknown class(es) found", "IncorrectM"); + .when(() -> EqualsVerifier.forPackage(CORRECT_PACKAGE, true).except(IncorrectM.class)) + .assertThrows(IllegalStateException.class) + .assertMessageContains("Unknown class(es) found", "IncorrectM"); } @Test public void succeed_whenCallingForPackageOnAPackageContainingFailingClasses_givenFailingClassesAreExceptedByPredicate() { - EqualsVerifier - .forPackage(INCORRECT_PACKAGE) - .except(c -> c.getSimpleName().contains("Incorrect")) - .verify(); + EqualsVerifier.forPackage(INCORRECT_PACKAGE).except(c -> c.getSimpleName().contains("Incorrect")).verify(); } @Test public void succeed_whenCallingForPackageRecursivelyOnAPackageContainingFailingClasses_givenFailingClassesAreExceptedByPredicate() { EqualsVerifier - .forPackage(INCORRECT_PACKAGE, true) - .except(c -> c.getSimpleName().contains("Incorrect")) - .verify(); + .forPackage(INCORRECT_PACKAGE, true) + .except(c -> c.getSimpleName().contains("Incorrect")) + .verify(); } @Test public void fail_whenCallingForPackageOnAPackageContainingFailingClasses_givenFailingClassesAreNotExceptedByPredicate() { ExpectedException - .when(() -> EqualsVerifier.forPackage(INCORRECT_PACKAGE).except(c -> false).verify()) - .assertFailure() - .assertMessageContains("EqualsVerifier found a problem in 2 classes"); + .when(() -> EqualsVerifier.forPackage(INCORRECT_PACKAGE).except(c -> false).verify()) + .assertFailure() + .assertMessageContains("EqualsVerifier found a problem in 2 classes"); } @Test public void fail_whenCallingForPackageRecursivelyOnAPackageContainingFailingClasses_givenFailingClassesAreNotExceptedByPredicate() { ExpectedException - .when(() -> - EqualsVerifier.forPackage(INCORRECT_PACKAGE, true).except(c -> false).verify() - ) - .assertFailure() - .assertMessageContains("EqualsVerifier found a problem in 4 classes"); + .when(() -> EqualsVerifier.forPackage(INCORRECT_PACKAGE, true).except(c -> false).verify()) + .assertFailure() + .assertMessageContains("EqualsVerifier found a problem in 4 classes"); } @Test @@ -274,9 +243,7 @@ public void succeed_whenCallingForPackageRecursivelyOnAPackageContainingFailingC @Test public void succeed_whenReportingOnSeveralCorrectClasses() { - List reports = EqualsVerifier - .forClasses(A.class, B.class, C.class) - .report(); + List reports = EqualsVerifier.forClasses(A.class, B.class, C.class).report(); assertEquals(3, reports.size()); assertSuccessful(reports.get(0), A.class); @@ -286,9 +253,7 @@ public void succeed_whenReportingOnSeveralCorrectClasses() { @Test public void fail_whenReportingOnOneIncorrectClass() { - List reports = EqualsVerifier - .forClasses(A.class, IncorrectM.class, C.class) - .report(); + List reports = EqualsVerifier.forClasses(A.class, IncorrectM.class, C.class).report(); assertEquals(3, reports.size()); assertSuccessful(reports.get(0), A.class); @@ -298,19 +263,14 @@ public void fail_whenReportingOnOneIncorrectClass() { @Test public void fail_whenReportingOnTwoIncorrectClasses() { - List reports = EqualsVerifier - .forClasses(A.class, IncorrectM.class, C.class, IncorrectN.class) - .report(); + List reports = + EqualsVerifier.forClasses(A.class, IncorrectM.class, C.class, IncorrectN.class).report(); assertEquals(4, reports.size()); assertSuccessful(reports.get(0), A.class); assertSuccessful(reports.get(2), C.class); assertUnsuccessful(reports.get(1), IncorrectM.class, "Subclass: equals is not final."); - assertUnsuccessful( - reports.get(3), - IncorrectN.class, - "Reflexivity: object does not equal itself:" - ); + assertUnsuccessful(reports.get(3), IncorrectN.class, "Reflexivity: object does not equal itself:"); } private void assertSuccessful(EqualsVerifierReport report, Class type) { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/OriginalStateTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/OriginalStateTest.java index dc4f7b5ea..12a2b54d8 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/OriginalStateTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/OriginalStateTest.java @@ -7,6 +7,7 @@ import static org.junit.jupiter.api.Assertions.fail; import java.util.Objects; + import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; @@ -49,13 +50,13 @@ public void allValuesReturnToOriginalState_whenEqualsVerifierIsFinishedWithExcep try { EqualsVerifier.forClass(FailingEqualsContainerContainer.class).verify(); fail("EqualsVerifier should have failed on FailingEqualsContainerContainer."); - } catch (AssertionError e) { + } + catch (AssertionError e) { // Make sure EV fails on a check that actually mutates fields. assertTrue(e.getMessage().contains("Mutability")); - } catch (Throwable ignored) { - fail( - "EqualsVerifier should have failed on FailingEqualsContainerContainer with a different exception." - ); + } + catch (Throwable ignored) { + fail("EqualsVerifier should have failed on FailingEqualsContainerContainer with a different exception."); } assertEquals(STATIC_FINAL, CorrectEquals.STATIC_FINAL_VALUE); diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/OutputTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/OutputTest.java index b06519506..c00583d4b 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/OutputTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/OutputTest.java @@ -19,75 +19,69 @@ public class OutputTest { @Test public void messageIsValidForSingleType_whenEqualsVerifierFails_givenExceptionIsGeneratedByEqualsVerifierItself() { ExpectedException - .when(() -> EqualsVerifier.forClass(Point.class).verify()) - .assertCause(AssertionException.class) - .assertMessageContains(Point.class.getSimpleName(), SEE_ALSO, WEBSITE_URL, SUFFIX); + .when(() -> EqualsVerifier.forClass(Point.class).verify()) + .assertCause(AssertionException.class) + .assertMessageContains(Point.class.getSimpleName(), SEE_ALSO, WEBSITE_URL, SUFFIX); } @Test public void messageIsValidForMultipleTypes_whenEqualsVerifierFails_givenExceptionIsGeneratedByEqualsVerifierItself() { ExpectedException - .when(() -> EqualsVerifier.forClasses(Point.class, MutablePoint.class).verify()) - .assertMessageContains(Point.class.getSimpleName()) - .assertMessageContains("---") - .assertMessageContainsOnce(SEE_ALSO) - .assertMessageContainsOnce(WEBSITE_URL) - .assertMessageContainsOnce(SUFFIX); + .when(() -> EqualsVerifier.forClasses(Point.class, MutablePoint.class).verify()) + .assertMessageContains(Point.class.getSimpleName()) + .assertMessageContains("---") + .assertMessageContainsOnce(SEE_ALSO) + .assertMessageContainsOnce(WEBSITE_URL) + .assertMessageContainsOnce(SUFFIX); } @Test public void errorDescriptionAppearsOnlyAtTopOfStacktrace_notInOneOfItsCauses() { ExpectedException - .when(() -> EqualsVerifier.forClass(Point.class).verify()) - .assertMessageContains("Subclass") - .assertCauseMessageDoesNotContain("Subclass"); + .when(() -> EqualsVerifier.forClass(Point.class).verify()) + .assertMessageContains("Subclass") + .assertCauseMessageDoesNotContain("Subclass"); } @Test public void messageIsValidAndCauseHasCause_whenEqualsVerifierFails_givenOriginalExceptionHasACause() { ExpectedException - .when(() -> EqualsVerifier.forClass(AssertionExceptionWithCauseThrower.class).verify()) - .assertMessageContains(AssertionExceptionWithCauseThrower.class.getSimpleName()) - .assertMessageContains(SEE_ALSO, WEBSITE_URL, SUFFIX, MESSAGE) - .assertMessageDoesNotContain(NullPointerException.class.getSimpleName()) - .assertCause(AssertionException.class) - .assertCause(NullPointerException.class); + .when(() -> EqualsVerifier.forClass(AssertionExceptionWithCauseThrower.class).verify()) + .assertMessageContains(AssertionExceptionWithCauseThrower.class.getSimpleName()) + .assertMessageContains(SEE_ALSO, WEBSITE_URL, SUFFIX, MESSAGE) + .assertMessageDoesNotContain(NullPointerException.class.getSimpleName()) + .assertCause(AssertionException.class) + .assertCause(NullPointerException.class); } @Test public void originalMessageIsPresentInOutput_whenEqualsVerifierFails_givenOriginalExceptionHasAMessage() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(UnsupportedOperationExceptionWithMessageThrower.class) - .verify() - ) - .assertMessageContains( - UnsupportedOperationExceptionWithMessageThrower.class.getSimpleName() - ) - .assertMessageContains(UnsupportedOperationException.class.getSimpleName()) - .assertMessageContains(SEE_ALSO, WEBSITE_URL, SUFFIX, MESSAGE) - .assertMessageDoesNotContainAfterRemove("EqualsVerifier null", "null") - .assertCause(UnsupportedOperationException.class) - .assertCauseMessageContains(MESSAGE); + .when(() -> EqualsVerifier.forClass(UnsupportedOperationExceptionWithMessageThrower.class).verify()) + .assertMessageContains(UnsupportedOperationExceptionWithMessageThrower.class.getSimpleName()) + .assertMessageContains(UnsupportedOperationException.class.getSimpleName()) + .assertMessageContains(SEE_ALSO, WEBSITE_URL, SUFFIX, MESSAGE) + .assertMessageDoesNotContainAfterRemove("EqualsVerifier null", "null") + .assertCause(UnsupportedOperationException.class) + .assertCauseMessageContains(MESSAGE); } @Test public void messageIsValidAndDoesNotContainStringNull_whenEqualsVerifierFails_givenOriginalExceptionIsBare() { ExpectedException - .when(() -> EqualsVerifier.forClass(IllegalStateExceptionThrower.class).verify()) - .assertMessageContains(IllegalStateExceptionThrower.class.getSimpleName()) - .assertMessageContains(SEE_ALSO, WEBSITE_URL, SUFFIX, "") - .assertMessageDoesNotContainAfterRemove("EqualsVerifier null", "null") - .assertCause(IllegalStateException.class); + .when(() -> EqualsVerifier.forClass(IllegalStateExceptionThrower.class).verify()) + .assertMessageContains(IllegalStateExceptionThrower.class.getSimpleName()) + .assertMessageContains(SEE_ALSO, WEBSITE_URL, SUFFIX, "") + .assertMessageDoesNotContainAfterRemove("EqualsVerifier null", "null") + .assertCause(IllegalStateException.class); } @Test public void noStackOverflowErrorIsThrown_whenClassIsARecursiveDatastructure() { ExpectedException - .when(() -> EqualsVerifier.forClass(Node.class).verify()) - .assertMessageContains(Node.class.getSimpleName(), SEE_ALSO, WEBSITE_URL, SUFFIX) - .assertNotCause(StackOverflowError.class); + .when(() -> EqualsVerifier.forClass(Node.class).verify()) + .assertMessageContains(Node.class.getSimpleName(), SEE_ALSO, WEBSITE_URL, SUFFIX) + .assertNotCause(StackOverflowError.class); } private static final class AssertionExceptionWithCauseThrower { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/RecursionTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/RecursionTest.java index 1c01935f6..4d001f9ae 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/RecursionTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/RecursionTest.java @@ -3,10 +3,11 @@ import static nl.jqno.equalsverifier.internal.testhelpers.Util.defaultEquals; import static nl.jqno.equalsverifier.internal.testhelpers.Util.defaultHashCode; -import com.google.common.collect.ImmutableList; import java.util.Collections; import java.util.List; import java.util.Objects; + +import com.google.common.collect.ImmutableList; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.internal.reflection.TypeTag; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; @@ -34,9 +35,9 @@ public void createSomeNodes() { @Test public void fail_whenDatastructureIsRecursive_givenItIsPassedInAsAClass() { ExpectedException - .when(() -> EqualsVerifier.forClass(Node.class).verify()) - .assertFailure() - .assertMessageContains(RECURSIVE_DATASTRUCTURE, PREFAB); + .when(() -> EqualsVerifier.forClass(Node.class).verify()) + .assertFailure() + .assertMessageContains(RECURSIVE_DATASTRUCTURE, PREFAB); } @Test @@ -62,85 +63,66 @@ public void succeed_whenDatastructureIsRecursive_givenPrefabValuesForFieldOfSupe @Test public void fail_whenFieldIsARecursiveType() { ExpectedException - .when(() -> EqualsVerifier.forClass(NodeContainer.class).verify()) - .assertFailure() - .assertMessageContains(RECURSIVE_DATASTRUCTURE, PREFAB, Node.class.getSimpleName()); + .when(() -> EqualsVerifier.forClass(NodeContainer.class).verify()) + .assertFailure() + .assertMessageContains(RECURSIVE_DATASTRUCTURE, PREFAB, Node.class.getSimpleName()); } @Test public void succeed_whenFieldIsARecursiveType_givenPrefabValues() { - EqualsVerifier - .forClass(NodeContainer.class) - .withPrefabValues(Node.class, red, blue) - .verify(); + EqualsVerifier.forClass(NodeContainer.class).withPrefabValues(Node.class, red, blue).verify(); } @Test public void succeed_whenFieldIsARecursiveType_givenPrefabValuesForField() { - EqualsVerifier - .forClass(NodeContainer.class) - .withPrefabValuesForField("node", red, blue) - .verify(); + EqualsVerifier.forClass(NodeContainer.class).withPrefabValuesForField("node", red, blue).verify(); } @Test public void succeed_whenFieldIsARecursiveType_givenPrefabValuesOfSuperclass() { - EqualsVerifier - .forClass(SubNodeContainer.class) - .withPrefabValues(Node.class, red, blue) - .verify(); + EqualsVerifier.forClass(SubNodeContainer.class).withPrefabValues(Node.class, red, blue).verify(); } @Test public void succeed_whenFieldIsARecursiveType_givenPrefabValuesForFieldOfSuperclass() { - EqualsVerifier - .forClass(SubNodeContainer.class) - .withPrefabValuesForField("node", red, blue) - .verify(); + EqualsVerifier.forClass(SubNodeContainer.class).withPrefabValuesForField("node", red, blue).verify(); } @Test public void fail_whenDatastructureIsRecursiveInGenerics() { ExpectedException - .when(() -> EqualsVerifier.forClass(Tree.class).verify()) - .assertFailure() - .assertMessageContains(RECURSIVE_DATASTRUCTURE, PREFAB); + .when(() -> EqualsVerifier.forClass(Tree.class).verify()) + .assertFailure() + .assertMessageContains(RECURSIVE_DATASTRUCTURE, PREFAB); } @Test public void succeed_whenDatastructureIsRecursiveInGenerics_givenPrefabValues() { - EqualsVerifier - .forClass(Tree.class) - .withPrefabValues(Tree.class, redTree, blueTree) - .verify(); + EqualsVerifier.forClass(Tree.class).withPrefabValues(Tree.class, redTree, blueTree).verify(); } @Test public void fail_whenFieldIsARecursiveTypeInGenerics() { ExpectedException - .when(() -> EqualsVerifier.forClass(TreeContainer.class).verify()) - .assertFailure() - .assertMessageContains(RECURSIVE_DATASTRUCTURE, PREFAB, Tree.class.getSimpleName()); + .when(() -> EqualsVerifier.forClass(TreeContainer.class).verify()) + .assertFailure() + .assertMessageContains(RECURSIVE_DATASTRUCTURE, PREFAB, Tree.class.getSimpleName()); } @Test public void succeed_whenFieldIsARecursiveTypeInGenerics_givenPrefabValues() { - EqualsVerifier - .forClass(TreeContainer.class) - .withPrefabValues(Tree.class, redTree, blueTree) - .verify(); + EqualsVerifier.forClass(TreeContainer.class).withPrefabValues(Tree.class, redTree, blueTree).verify(); } @Test public void giveCorrectErrorMessage_whenFieldIsInstantiatedUsingReflectiveFactory() { ExpectedException - .when(() -> EqualsVerifier.forClass(ImmutableListTree.class).verify()) - .assertFailure() - .assertMessageContains( - RECURSIVE_DATASTRUCTURE, - ImmutableListTree.class.getSimpleName(), - new TypeTag(ImmutableList.class, new TypeTag(ImmutableListTree.class)).toString() - ); + .when(() -> EqualsVerifier.forClass(ImmutableListTree.class).verify()) + .assertFailure() + .assertMessageContains( + RECURSIVE_DATASTRUCTURE, + ImmutableListTree.class.getSimpleName(), + new TypeTag(ImmutableList.class, new TypeTag(ImmutableListTree.class)).toString()); } @Test diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/ReportTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/ReportTest.java index e2e1ec376..8dcbc0140 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/ReportTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/ReportTest.java @@ -31,10 +31,7 @@ public void containsAppropriateErrorMessageAndExceptionWhenClassIsIncorrect() { assertFalse(report.isSuccessful()); assertThat( report.getMessage(), - startsWith( - "EqualsVerifier found a problem in class nl.jqno.equalsverifier.testhelpers.types.Point" - ) - ); + startsWith("EqualsVerifier found a problem in class nl.jqno.equalsverifier.testhelpers.types.Point")); assertEquals(AssertionException.class, report.getCause().getClass()); assertNull(report.getCause().getMessage()); } @@ -45,7 +42,8 @@ public void reportReturnsTheSameInformationAsVerify() { try { EqualsVerifier.forClass(Point.class).verify(); fail("Should have failed"); - } catch (AssertionError e) { + } + catch (AssertionError e) { assertEquals(e.getMessage(), report.getMessage()); assertEquals(e.getCause().getClass(), report.getCause().getClass()); diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/WithGenericPrefabValuesTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/WithGenericPrefabValuesTest.java index 075ab4dbf..23be3c417 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/WithGenericPrefabValuesTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/WithGenericPrefabValuesTest.java @@ -16,197 +16,167 @@ public class WithGenericPrefabValuesTest { @Test public void sanityCheck() { EqualsVerifier - .forClass(SingleGenericContainer.class) - .withPrefabValues( - SingleGenericContainer.class, - new SingleGenericContainer<>(1), - new SingleGenericContainer<>(2) - ) - .verify(); + .forClass(SingleGenericContainer.class) + .withPrefabValues( + SingleGenericContainer.class, + new SingleGenericContainer<>(1), + new SingleGenericContainer<>(2)) + .verify(); EqualsVerifier - .forClass(DoubleGenericContainer.class) - .withPrefabValues( - DoubleGenericContainer.class, - new DoubleGenericContainer<>(1, 1), - new DoubleGenericContainer<>(2, 2) - ) - .verify(); + .forClass(DoubleGenericContainer.class) + .withPrefabValues( + DoubleGenericContainer.class, + new DoubleGenericContainer<>(1, 1), + new DoubleGenericContainer<>(2, 2)) + .verify(); } @Test public void fail_whenRegularPrefabValuesOfWrongTypeAreUsed_given1GenericParameter() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(SingleGenericContainerContainer.class) - .withPrefabValues( - SingleGenericContainer.class, - new SingleGenericContainer<>(1), - new SingleGenericContainer<>(2) - ) - .verify() - ) - .assertFailure() - .assertCause(ClassCastException.class) - .assertMessageContains( - "Generics", - "for " + SingleGenericContainer.class.getSimpleName() - ); + .when( + () -> EqualsVerifier + .forClass(SingleGenericContainerContainer.class) + .withPrefabValues( + SingleGenericContainer.class, + new SingleGenericContainer<>(1), + new SingleGenericContainer<>(2)) + .verify()) + .assertFailure() + .assertCause(ClassCastException.class) + .assertMessageContains("Generics", "for " + SingleGenericContainer.class.getSimpleName()); } @Test public void fail_whenRegularPrefabValuesOfWrongTypeAreUsedAndMarkedAsNonnull_given1GenericParameter() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(SingleGenericContainerContainer.class) - .withNonnullFields("string", "integer") - .withPrefabValues( - SingleGenericContainer.class, - new SingleGenericContainer<>(1), - new SingleGenericContainer<>(2) - ) - .verify() - ) - .assertFailure() - .assertCause(ClassCastException.class) - .assertMessageContains("Generics", "for the type that triggered the exception"); + .when( + () -> EqualsVerifier + .forClass(SingleGenericContainerContainer.class) + .withNonnullFields("string", "integer") + .withPrefabValues( + SingleGenericContainer.class, + new SingleGenericContainer<>(1), + new SingleGenericContainer<>(2)) + .verify()) + .assertFailure() + .assertCause(ClassCastException.class) + .assertMessageContains("Generics", "for the type that triggered the exception"); } @Test public void succeed_whenPrefabValuesMatchGenericParameterInClassUnderTest_given1GenericParameter() { EqualsVerifier - .forClass(SingleGenericContainerContainer.class) - .withGenericPrefabValues(SingleGenericContainer.class, SingleGenericContainer::new) - .verify(); + .forClass(SingleGenericContainerContainer.class) + .withGenericPrefabValues(SingleGenericContainer.class, SingleGenericContainer::new) + .verify(); } @Test public void throw_whenTypeIsNull_given1GenericParameter() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(SingleGenericContainerContainer.class) - .withGenericPrefabValues(null, SingleGenericContainer::new) - ) - .assertThrows(NullPointerException.class); + .when( + () -> EqualsVerifier + .forClass(SingleGenericContainerContainer.class) + .withGenericPrefabValues(null, SingleGenericContainer::new)) + .assertThrows(NullPointerException.class); } @Test public void throw_whenFactoryIsNull_given1GenericParameter() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(SingleGenericContainerContainer.class) - .withGenericPrefabValues(SingleGenericContainer.class, (Func1) null) - ) - .assertThrows(NullPointerException.class); + .when( + () -> EqualsVerifier + .forClass(SingleGenericContainerContainer.class) + .withGenericPrefabValues(SingleGenericContainer.class, (Func1) null)) + .assertThrows(NullPointerException.class); } @Test public void throw_whenFactoryHas2Parameters_given1GenericParameter() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(SingleGenericContainerContainer.class) - .withGenericPrefabValues( - SingleGenericContainer.class, - (Func2) (a, b) -> new SingleGenericContainer<>(a) - ) - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "Precondition", - "number of generic type parameters doesn't match" - ); + .when( + () -> EqualsVerifier + .forClass(SingleGenericContainerContainer.class) + .withGenericPrefabValues( + SingleGenericContainer.class, + (Func2) (a, b) -> new SingleGenericContainer<>(a))) + .assertThrows(IllegalStateException.class) + .assertMessageContains("Precondition", "number of generic type parameters doesn't match"); } @Test public void fail_whenRegularPrefabValuesOfWrongTypeAreUsed_given2GenericParameters() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(DoubleGenericContainerContainer.class) - .withPrefabValues( - DoubleGenericContainer.class, - new DoubleGenericContainer<>(1, 1), - new DoubleGenericContainer<>(2, 2) - ) - .verify() - ) - .assertFailure() - .assertCause(ClassCastException.class) - .assertMessageContains( - "Generics", - "for " + DoubleGenericContainer.class.getSimpleName() - ); + .when( + () -> EqualsVerifier + .forClass(DoubleGenericContainerContainer.class) + .withPrefabValues( + DoubleGenericContainer.class, + new DoubleGenericContainer<>(1, 1), + new DoubleGenericContainer<>(2, 2)) + .verify()) + .assertFailure() + .assertCause(ClassCastException.class) + .assertMessageContains("Generics", "for " + DoubleGenericContainer.class.getSimpleName()); } @Test public void fail_whenRegularPrefabValuesOfWrongTypeAreUsedAndMarkedAsNonnull_given2GenericParameters() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(DoubleGenericContainerContainer.class) - .withNonnullFields("stringBoolean", "integerByte") - .withPrefabValues( - DoubleGenericContainer.class, - new DoubleGenericContainer<>(1, 1), - new DoubleGenericContainer<>(2, 2) - ) - .verify() - ) - .assertFailure() - .assertCause(ClassCastException.class) - .assertMessageContains("Generics", "for the type that triggered the exception"); + .when( + () -> EqualsVerifier + .forClass(DoubleGenericContainerContainer.class) + .withNonnullFields("stringBoolean", "integerByte") + .withPrefabValues( + DoubleGenericContainer.class, + new DoubleGenericContainer<>(1, 1), + new DoubleGenericContainer<>(2, 2)) + .verify()) + .assertFailure() + .assertCause(ClassCastException.class) + .assertMessageContains("Generics", "for the type that triggered the exception"); } @Test public void succeed_whenPrefabValuesMatchGenericParametersInClassUnderTest_given2GenericParameters() { EqualsVerifier - .forClass(DoubleGenericContainerContainer.class) - .withGenericPrefabValues(DoubleGenericContainer.class, DoubleGenericContainer::new) - .verify(); + .forClass(DoubleGenericContainerContainer.class) + .withGenericPrefabValues(DoubleGenericContainer.class, DoubleGenericContainer::new) + .verify(); } @Test public void throw_whenTypeIsNull_given2GenericParameters() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(DoubleGenericContainerContainer.class) - .withGenericPrefabValues(null, DoubleGenericContainer::new) - ) - .assertThrows(NullPointerException.class); + .when( + () -> EqualsVerifier + .forClass(DoubleGenericContainerContainer.class) + .withGenericPrefabValues(null, DoubleGenericContainer::new)) + .assertThrows(NullPointerException.class); } @Test public void throw_whenFactoryIsNull_given2GenericParameters() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(DoubleGenericContainerContainer.class) - .withGenericPrefabValues(DoubleGenericContainer.class, (Func2) null) - ) - .assertThrows(NullPointerException.class); + .when( + () -> EqualsVerifier + .forClass(DoubleGenericContainerContainer.class) + .withGenericPrefabValues(DoubleGenericContainer.class, (Func2) null)) + .assertThrows(NullPointerException.class); } @Test public void throw_whenFactoryHas1Parameter_given2GenericParameters() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(DoubleGenericContainerContainer.class) - .withGenericPrefabValues( - DoubleGenericContainer.class, - (Func1) (a -> new DoubleGenericContainer<>(a, a)) - ) - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "Precondition", - "number of generic type parameters doesn't match" - ); + .when( + () -> EqualsVerifier + .forClass(DoubleGenericContainerContainer.class) + .withGenericPrefabValues( + DoubleGenericContainer.class, + (Func1) (a -> new DoubleGenericContainer<>(a, a)))) + .assertThrows(IllegalStateException.class) + .assertMessageContains("Precondition", "number of generic type parameters doesn't match"); } } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/WithPrefabValuesForFieldTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/WithPrefabValuesForFieldTest.java index 39b88a76c..d4ab8013e 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/WithPrefabValuesForFieldTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/WithPrefabValuesForFieldTest.java @@ -3,6 +3,7 @@ import java.time.LocalDate; import java.time.Month; import java.util.*; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; @@ -19,101 +20,85 @@ public class WithPrefabValuesForFieldTest { @Test public void fail_whenClassHasSinglePrecondition() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(SinglePrecondition.class) - .suppress(Warning.NULL_FIELDS) - .verify() - ) - .assertFailure() - .assertMessageContains("x coordinate must be"); + .when(() -> EqualsVerifier.forClass(SinglePrecondition.class).suppress(Warning.NULL_FIELDS).verify()) + .assertFailure() + .assertMessageContains("x coordinate must be"); } @Test public void succeed_whenClassHasSinglePrecondition_givenPrefabValuesForField() { - EqualsVerifier - .forClass(SinglePrecondition.class) - .withPrefabValuesForField("point", pRed, pBlue) - .verify(); + EqualsVerifier.forClass(SinglePrecondition.class).withPrefabValuesForField("point", pRed, pBlue).verify(); } @Test public void fail_whenClassHasDualPrecondition() { ExpectedException - .when(() -> EqualsVerifier.forClass(DualPrecondition.class).verify()) - .assertFailure() - .assertMessageContains("x must be between"); + .when(() -> EqualsVerifier.forClass(DualPrecondition.class).verify()) + .assertFailure() + .assertMessageContains("x must be between"); } @Test public void fail_whenClassHasDualPrecondition_givenPrefabValuesForOnlyOneField() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(DualPrecondition.class) - .withPrefabValuesForField("x", iRed, iBlue) - .verify() - ) - .assertFailure() - .assertMessageContains("y must be between"); + .when( + () -> EqualsVerifier + .forClass(DualPrecondition.class) + .withPrefabValuesForField("x", iRed, iBlue) + .verify()) + .assertFailure() + .assertMessageContains("y must be between"); } @Test public void succeed_whenClassHasDualPrecondition_givenPrefabValueForBothFields() { EqualsVerifier - .forClass(DualPrecondition.class) - .withPrefabValuesForField("x", iRed, iBlue) - .withPrefabValuesForField("y", 505, 555) - .verify(); + .forClass(DualPrecondition.class) + .withPrefabValuesForField("x", iRed, iBlue) + .withPrefabValuesForField("y", 505, 555) + .verify(); } @Test public void throw_whenFieldDoesNotExistInClass() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(SinglePrecondition.class) - .withPrefabValuesForField("doesnt_exist", 1, 2) - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains("Precondition:", "does not contain field doesnt_exist"); + .when( + () -> EqualsVerifier + .forClass(SinglePrecondition.class) + .withPrefabValuesForField("doesnt_exist", 1, 2)) + .assertThrows(IllegalStateException.class) + .assertMessageContains("Precondition:", "does not contain field doesnt_exist"); } @Test public void throw_whenFirstPrefabValueIsNull() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(SinglePrecondition.class) - .withPrefabValuesForField("point", null, pBlue) - ) - .assertThrows(NullPointerException.class); + .when( + () -> EqualsVerifier + .forClass(SinglePrecondition.class) + .withPrefabValuesForField("point", null, pBlue)) + .assertThrows(NullPointerException.class); } @Test public void throw_whenSecondPrefabValueIsNull() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(SinglePrecondition.class) - .withPrefabValuesForField("point", pRed, null) - ) - .assertThrows(NullPointerException.class); + .when( + () -> EqualsVerifier + .forClass(SinglePrecondition.class) + .withPrefabValuesForField("point", pRed, null)) + .assertThrows(NullPointerException.class); } @Test public void throw_whenThePrefabValuesAreTheSame() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(SinglePrecondition.class) - .withPrefabValuesForField("point", pRed, pRed) - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "Precondition", - "both prefab values of type FinalPoint are equal" - ); + .when( + () -> EqualsVerifier + .forClass(SinglePrecondition.class) + .withPrefabValuesForField("point", pRed, pRed)) + .assertThrows(IllegalStateException.class) + .assertMessageContains("Precondition", "both prefab values of type FinalPoint are equal"); } @Test @@ -122,59 +107,44 @@ public void throw_whenThePrefabValuesAreEqual() { FinalPoint red2 = new FinalPoint(3, 4); ExpectedException - .when(() -> - EqualsVerifier - .forClass(SinglePrecondition.class) - .withPrefabValuesForField("point", red1, red2) - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "Precondition", - "both prefab values of type FinalPoint are equal" - ); + .when( + () -> EqualsVerifier + .forClass(SinglePrecondition.class) + .withPrefabValuesForField("point", red1, red2)) + .assertThrows(IllegalStateException.class) + .assertMessageContains("Precondition", "both prefab values of type FinalPoint are equal"); } @Test public void throw_whenFieldsDontMatch() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(SinglePrecondition.class) - .withPrefabValuesForField("point", 1, 2) - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "Precondition", - "for field point should be of type FinalPoint but are" - ); + .when(() -> EqualsVerifier.forClass(SinglePrecondition.class).withPrefabValuesForField("point", 1, 2)) + .assertThrows(IllegalStateException.class) + .assertMessageContains("Precondition", "for field point should be of type FinalPoint but are"); } @Test public void dontThrow_whenAddingPrefabValuesFromAnotherModuleAndThereforeARedCopyCantBeMade() { EqualsVerifier - .forClass(OtherModuleContainer.class) - .withPrefabValuesForField("date", LocalDate.of(2024, 9, 18), LocalDate.of(2024, 9, 19)) - .verify(); + .forClass(OtherModuleContainer.class) + .withPrefabValuesForField("date", LocalDate.of(2024, 9, 18), LocalDate.of(2024, 9, 19)) + .verify(); } @Test public void succeed_whenPrefabForArrayIsOverridden() { EqualsVerifier - .forClass(ThrowingArrayContainer.class) - .withPrefabValuesForField("field", new int[] { 1, 2, 3 }, new int[] { 4, 5, 6 }) - .verify(); + .forClass(ThrowingArrayContainer.class) + .withPrefabValuesForField("field", new int[] { 1, 2, 3 }, new int[] { 4, 5, 6 }) + .verify(); } @Test public void succeed_whenClassContainsSomethingThatAllowsSubclassesAndASubclassIsGiven() { EqualsVerifier - .forClass(ListContainer.class) - .withPrefabValuesForField( - "list", - Collections.singletonList("x"), - Collections.singletonList("y") - ) - .verify(); + .forClass(ListContainer.class) + .withPrefabValuesForField("list", Collections.singletonList("x"), Collections.singletonList("y")) + .verify(); } @Test @@ -182,13 +152,9 @@ public void succeed_whenClassContainsAGenericInterfaceThatRefersToItself() { DifficultGeneric one = new DifficultGeneric(new ArrayList<>()); DifficultGeneric two = new DifficultGeneric(null); EqualsVerifier - .forClass(DifficultGeneric.class) - .withPrefabValuesForField( - "list", - Collections.singletonList(one), - Collections.singletonList(two) - ) - .verify(); + .forClass(DifficultGeneric.class) + .withPrefabValuesForField("list", Collections.singletonList(one), Collections.singletonList(two)) + .verify(); } static final class SinglePrecondition { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/WithPrefabValuesTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/WithPrefabValuesTest.java index fdc47d529..324f91d4a 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/WithPrefabValuesTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/integration/operational/WithPrefabValuesTest.java @@ -1,6 +1,7 @@ package nl.jqno.equalsverifier.integration.operational; import java.time.LocalDate; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; import nl.jqno.equalsverifier.testhelpers.types.FinalPoint; @@ -13,58 +14,45 @@ public class WithPrefabValuesTest { @Test public void succeed_whenPrefabValuesAreOfSameTypeAsClassUnderTest() { - EqualsVerifier - .forClass(FinalPoint.class) - .withPrefabValues(FinalPoint.class, red, blue) - .verify(); + EqualsVerifier.forClass(FinalPoint.class).withPrefabValues(FinalPoint.class, red, blue).verify(); } @Test public void throw_whenTypeIsNull() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(WithPrefabValuesTest.class) - .withPrefabValues(null, red, blue) - ) - .assertThrows(NullPointerException.class); + .when(() -> EqualsVerifier.forClass(WithPrefabValuesTest.class).withPrefabValues(null, red, blue)) + .assertThrows(NullPointerException.class); } @Test public void throw_whenFirstPrefabValueIsNull() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(WithPrefabValuesTest.class) - .withPrefabValues(FinalPoint.class, null, blue) - ) - .assertThrows(NullPointerException.class); + .when( + () -> EqualsVerifier + .forClass(WithPrefabValuesTest.class) + .withPrefabValues(FinalPoint.class, null, blue)) + .assertThrows(NullPointerException.class); } @Test public void throw_whenSecondPrefabValueIsNull() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(WithPrefabValuesTest.class) - .withPrefabValues(FinalPoint.class, red, null) - ) - .assertThrows(NullPointerException.class); + .when( + () -> EqualsVerifier + .forClass(WithPrefabValuesTest.class) + .withPrefabValues(FinalPoint.class, red, null)) + .assertThrows(NullPointerException.class); } @Test public void throw_whenThePrefabValuesAreTheSame() { ExpectedException - .when(() -> - EqualsVerifier - .forClass(WithPrefabValuesTest.class) - .withPrefabValues(FinalPoint.class, red, red) - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "Precondition", - "both prefab values of type FinalPoint are equal" - ); + .when( + () -> EqualsVerifier + .forClass(WithPrefabValuesTest.class) + .withPrefabValues(FinalPoint.class, red, red)) + .assertThrows(IllegalStateException.class) + .assertMessageContains("Precondition", "both prefab values of type FinalPoint are equal"); } @Test @@ -73,27 +61,19 @@ public void throw_whenThePrefabValuesAreEqual() { FinalPoint red2 = new FinalPoint(4, 4); ExpectedException - .when(() -> - EqualsVerifier - .forClass(WithPrefabValuesTest.class) - .withPrefabValues(FinalPoint.class, red1, red2) - ) - .assertThrows(IllegalStateException.class) - .assertMessageContains( - "Precondition", - "both prefab values of type FinalPoint are equal" - ); + .when( + () -> EqualsVerifier + .forClass(WithPrefabValuesTest.class) + .withPrefabValues(FinalPoint.class, red1, red2)) + .assertThrows(IllegalStateException.class) + .assertMessageContains("Precondition", "both prefab values of type FinalPoint are equal"); } @Test public void dontThrow_whenAddingPrefabValuesFromAnotherModuleAndThereforeARedCopyCantBeMade() { EqualsVerifier - .forClass(FinalPoint.class) - .withPrefabValues( - LocalDate.class, - LocalDate.of(2018, 12, 24), - LocalDate.of(2018, 12, 25) - ) - .verify(); + .forClass(FinalPoint.class) + .withPrefabValues(LocalDate.class, LocalDate.of(2018, 12, 24), LocalDate.of(2018, 12, 25)) + .verify(); } } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/architecture/ArchitectureTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/architecture/ArchitectureTest.java index 014186834..58f371ee2 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/architecture/ArchitectureTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/architecture/ArchitectureTest.java @@ -16,81 +16,70 @@ public final class ArchitectureTest { @ArchTest public static final ArchRule ONLY_VINTAGE_INSTANTIATORS_CAN_USE_VINTAGE_REFLECTION = noClasses() - .that() - .resideOutsideOfPackage("nl.jqno.equalsverifier.internal.instantiation.vintage..") - .and() - .doNotBelongToAnyOf( - JavaApiPrefabValues.class, - // 👇 Test classes - FactoryCacheFactory.class - ) - .should() - .accessClassesThat() - .resideInAPackage("nl.jqno.equalsverifier.internal.instantiation.vintage.prefabvalues..") - .orShould() - .accessClassesThat() - .resideInAPackage("nl.jqno.equalsverifier.internal.instantiation.vintage.reflection.."); + .that() + .resideOutsideOfPackage("nl.jqno.equalsverifier.internal.instantiation.vintage..") + .and() + .doNotBelongToAnyOf( + JavaApiPrefabValues.class, + // 👇 Test classes + FactoryCacheFactory.class) + .should() + .accessClassesThat() + .resideInAPackage("nl.jqno.equalsverifier.internal.instantiation.vintage.prefabvalues..") + .orShould() + .accessClassesThat() + .resideInAPackage("nl.jqno.equalsverifier.internal.instantiation.vintage.reflection.."); @ArchTest public static final ArchRule DONT_USE_VINTAGE_REFLECTION_DIRECTLY = noClasses() - .that() - .resideInAPackage("nl.jqno.equalsverifier.internal.checkers..") - .should() - .accessClassesThat() - .areAssignableTo(ClassAccessor.class) - .orShould() - .accessClassesThat() - .areAssignableTo(ObjectAccessor.class) - .orShould() - .accessClassesThat() - .areAssignableTo(FieldModifier.class); + .that() + .resideInAPackage("nl.jqno.equalsverifier.internal.checkers..") + .should() + .accessClassesThat() + .areAssignableTo(ClassAccessor.class) + .orShould() + .accessClassesThat() + .areAssignableTo(ObjectAccessor.class) + .orShould() + .accessClassesThat() + .areAssignableTo(FieldModifier.class); @ArchTest public static final ArchRule APACHE_COMMONS = noClasses() - .that() - .haveNameNotMatching(".*SuperclassTest.*") - .should() - .accessClassesThat() - .resideInAPackage("org.apache.commons.."); + .that() + .haveNameNotMatching(".*SuperclassTest.*") + .should() + .accessClassesThat() + .resideInAPackage("org.apache.commons.."); @ArchTest - public static final ArchRule AWT = dontAllowImports_outsideFactoryProvidersAndTests_from( - "java.awt.common.." - ); + public static final ArchRule AWT = dontAllowImports_outsideFactoryProvidersAndTests_from("java.awt.common.."); @ArchTest - public static final ArchRule GUAVA = dontAllowImports_outsideFactoryProvidersAndTests_from( - "com.google.common.." - ); + public static final ArchRule GUAVA = dontAllowImports_outsideFactoryProvidersAndTests_from("com.google.common.."); @ArchTest - public static final ArchRule JAVAFX = dontAllowImports_outsideFactoryProvidersAndTests_from( - "javafx.." - ); + public static final ArchRule JAVAFX = dontAllowImports_outsideFactoryProvidersAndTests_from("javafx.."); @ArchTest - public static final ArchRule JODA = dontAllowImports_outsideFactoryProvidersAndTests_from( - "org.joda.." - ); + public static final ArchRule JODA = dontAllowImports_outsideFactoryProvidersAndTests_from("org.joda.."); private static final String FACTORYPROVIDER_PATTERN = - "nl.jqno.equalsverifier.internal.instantiation.vintage.prefabvalues.factoryproviders.."; + "nl.jqno.equalsverifier.internal.instantiation.vintage.prefabvalues.factoryproviders.."; private static final String TEST_CLASS_PATTERN = ".*Test(\\$.*)?$"; private ArchitectureTest() { // Do not instantiate } - private static ArchRule dontAllowImports_outsideFactoryProvidersAndTests_from( - String packageName - ) { + private static ArchRule dontAllowImports_outsideFactoryProvidersAndTests_from(String packageName) { return noClasses() - .that() - .resideOutsideOfPackage(FACTORYPROVIDER_PATTERN) - .and() - .haveNameNotMatching(TEST_CLASS_PATTERN) - .should() - .accessClassesThat() - .resideInAPackage(packageName); + .that() + .resideOutsideOfPackage(FACTORYPROVIDER_PATTERN) + .and() + .haveNameNotMatching(TEST_CLASS_PATTERN) + .should() + .accessClassesThat() + .resideInAPackage(packageName); } } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/exceptions/RecursionExceptionTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/exceptions/RecursionExceptionTest.java index 6b118672c..4504db033 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/exceptions/RecursionExceptionTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/exceptions/RecursionExceptionTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.LinkedHashSet; + import nl.jqno.equalsverifier.internal.reflection.TypeTag; import nl.jqno.equalsverifier.testhelpers.types.Point; import org.junit.jupiter.api.Test; diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/InstanceCreatorTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/InstanceCreatorTest.java index 0ca65bbe0..ffdc46855 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/InstanceCreatorTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/InstanceCreatorTest.java @@ -5,6 +5,7 @@ import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; + import nl.jqno.equalsverifier.internal.reflection.ClassProbe; import org.junit.jupiter.api.Test; import org.objenesis.Objenesis; diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/SubjectCreatorTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/SubjectCreatorTest.java index 46a603f0c..9bf57cea5 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/SubjectCreatorTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/SubjectCreatorTest.java @@ -6,6 +6,7 @@ import java.lang.reflect.Field; import java.util.Objects; import java.util.Optional; + import nl.jqno.equalsverifier.internal.exceptions.NoValueException; import nl.jqno.equalsverifier.internal.reflection.FieldCache; import nl.jqno.equalsverifier.internal.reflection.Tuple; @@ -25,18 +26,11 @@ public class SubjectCreatorTest { private static final String S_RED = "abc"; private static final String S_BLUE = "xyz"; - private Configuration config = ConfigurationHelper.emptyConfiguration( - SomeClass.class - ); + private Configuration config = ConfigurationHelper.emptyConfiguration(SomeClass.class); private ValueProvider valueProvider = new SubjectCreatorTestValueProvider(); private FieldCache fieldCache = new FieldCache(); private Objenesis objenesis = new ObjenesisStd(); - private SubjectCreator sut = new SubjectCreator<>( - config, - valueProvider, - fieldCache, - objenesis - ); + private SubjectCreator sut = new SubjectCreator<>(config, valueProvider, fieldCache, objenesis); private Field fieldX; private Field fieldI; @@ -198,10 +192,7 @@ public void copyIntoSubclass() { public void noValueFound() { sut = new SubjectCreator<>(config, new NoValueProvider(), fieldCache, objenesis); - ExpectedException - .when(() -> sut.plain()) - .assertThrows(NoValueException.class) - .assertDescriptionContains("int"); + ExpectedException.when(() -> sut.plain()).assertThrows(NoValueException.class).assertDescriptionContains("int"); assertEquals(expected, actual); } @@ -281,12 +272,10 @@ public boolean equals(Object obj) { return false; } SomeClass other = (SomeClass) obj; - return ( - other.canEqual(this) && - super.equals(other) && - Objects.equals(i, other.i) && - Objects.equals(s, other.s) - ); + return other.canEqual(this) + && super.equals(other) + && Objects.equals(i, other.i) + && Objects.equals(s, other.s); } @Override diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/FactoryCacheTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/FactoryCacheTest.java index a91e73794..6e34ba5cf 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/FactoryCacheTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/FactoryCacheTest.java @@ -9,17 +9,10 @@ public class FactoryCacheTest { private static final Class STRING_CLASS = String.class; - private static final PrefabValueFactory STRING_FACTORY = new SimpleFactory<>( - "red", - "blue", - new String("red") - ); + private static final PrefabValueFactory STRING_FACTORY = + new SimpleFactory<>("red", "blue", new String("red")); private static final Class INT_CLASS = int.class; - private static final PrefabValueFactory INT_FACTORY = new SimpleFactory<>( - 42, - 1337, - 42 - ); + private static final PrefabValueFactory INT_FACTORY = new SimpleFactory<>(42, 1337, 42); private final FactoryCache cache = new FactoryCache(); diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/VintageValueProviderCreatorTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/VintageValueProviderCreatorTest.java index 934543a92..c33ed35ba 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/VintageValueProviderCreatorTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/VintageValueProviderCreatorTest.java @@ -82,51 +82,39 @@ public void oneStepRecursiveType() { @Test public void dontAddOneStepRecursiveType() { - ExpectedException - .when(() -> valueProvider.giveRed(NODE_TAG)) - .assertThrows(RecursionException.class); + ExpectedException.when(() -> valueProvider.giveRed(NODE_TAG)).assertThrows(RecursionException.class); } @Test public void oneStepRecursiveArrayType() { - factoryCache.put( - NodeArray.class, - values(new NodeArray(), new NodeArray(), new NodeArray()) - ); + factoryCache.put(NodeArray.class, values(new NodeArray(), new NodeArray(), new NodeArray())); valueProvider = new VintageValueProvider(factoryCache, objenesis); valueProvider.giveRed(NODE_ARRAY_TAG); } @Test public void dontAddOneStepRecursiveArrayType() { - ExpectedException - .when(() -> valueProvider.giveRed(NODE_ARRAY_TAG)) - .assertThrows(RecursionException.class); + ExpectedException.when(() -> valueProvider.giveRed(NODE_ARRAY_TAG)).assertThrows(RecursionException.class); } @Test public void addTwoStepRecursiveType() { - factoryCache.put( - TwoStepNodeB.class, - values(new TwoStepNodeB(), new TwoStepNodeB(), new TwoStepNodeB()) - ); + factoryCache.put(TwoStepNodeB.class, values(new TwoStepNodeB(), new TwoStepNodeB(), new TwoStepNodeB())); valueProvider = new VintageValueProvider(factoryCache, objenesis); valueProvider.giveRed(TWOSTEP_NODE_A_TAG); } @Test public void dontAddTwoStepRecursiveType() { - ExpectedException - .when(() -> valueProvider.giveRed(TWOSTEP_NODE_A_TAG)) - .assertThrows(RecursionException.class); + ExpectedException.when(() -> valueProvider.giveRed(TWOSTEP_NODE_A_TAG)).assertThrows(RecursionException.class); } @Test public void twoStepRecursiveArrayType() { - factoryCache.put( - TwoStepNodeArrayB.class, - values(new TwoStepNodeArrayB(), new TwoStepNodeArrayB(), new TwoStepNodeArrayB()) - ); + factoryCache + .put( + TwoStepNodeArrayB.class, + values(new TwoStepNodeArrayB(), new TwoStepNodeArrayB(), new TwoStepNodeArrayB())); valueProvider = new VintageValueProvider(factoryCache, objenesis); valueProvider.giveRed(TWOSTEP_NODE_ARRAY_A_TAG); } @@ -134,8 +122,8 @@ public void twoStepRecursiveArrayType() { @Test public void dontAddTwoStepRecursiveArrayType() { ExpectedException - .when(() -> valueProvider.giveRed(TWOSTEP_NODE_ARRAY_A_TAG)) - .assertThrows(RecursionException.class); + .when(() -> valueProvider.giveRed(TWOSTEP_NODE_ARRAY_A_TAG)) + .assertThrows(RecursionException.class); } @Test @@ -146,21 +134,18 @@ public void sameClassTwiceButNoRecursion() { @Test public void recursiveWithAnotherFieldFirst() { ExpectedException - .when(() -> valueProvider.giveRed(new TypeTag(RecursiveWithAnotherFieldFirst.class))) - .assertThrows(RecursionException.class) - .assertDescriptionContains(RecursiveWithAnotherFieldFirst.class.getSimpleName()) - .assertDescriptionDoesNotContain(RecursiveThisIsTheOtherField.class.getSimpleName()); + .when(() -> valueProvider.giveRed(new TypeTag(RecursiveWithAnotherFieldFirst.class))) + .assertThrows(RecursionException.class) + .assertDescriptionContains(RecursiveWithAnotherFieldFirst.class.getSimpleName()) + .assertDescriptionDoesNotContain(RecursiveThisIsTheOtherField.class.getSimpleName()); } @Test public void exceptionMessage() { ExpectedException - .when(() -> valueProvider.giveRed(TWOSTEP_NODE_A_TAG)) - .assertThrows(RecursionException.class) - .assertDescriptionContains( - TwoStepNodeA.class.getSimpleName(), - TwoStepNodeB.class.getSimpleName() - ); + .when(() -> valueProvider.giveRed(TWOSTEP_NODE_A_TAG)) + .assertThrows(RecursionException.class) + .assertDescriptionContains(TwoStepNodeA.class.getSimpleName(), TwoStepNodeB.class.getSimpleName()); } @Test diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/VintageValueProviderTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/VintageValueProviderTest.java index b51060445..ff78588ba 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/VintageValueProviderTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/VintageValueProviderTest.java @@ -8,6 +8,7 @@ import static org.junit.jupiter.api.Assertions.fail; import java.util.*; + import nl.jqno.equalsverifier.internal.instantiation.vintage.prefabvalues.factories.PrefabValueFactory; import nl.jqno.equalsverifier.internal.reflection.Tuple; import nl.jqno.equalsverifier.internal.reflection.TypeTag; @@ -46,10 +47,7 @@ public void sanityTestFactoryIncreasesStringLength() { @Test public void provide() { Optional> actual = vp.provide(POINT_TAG); - assertEquals( - Tuple.of(new Point(42, 42), new Point(1337, 1337), new Point(42, 42)), - actual.get() - ); + assertEquals(Tuple.of(new Point(42, 42), new Point(1337, 1337), new Point(42, 42)), actual.get()); } @Test @@ -153,18 +151,18 @@ public void addLazyFactoryIsLazy() { TypeTag throwingInitializerTag = new TypeTag(ThrowingInitializer.class); // Shouldn't throw, because constructing PrefabValues doesn't instantiate objects: - factoryCache.put( - ThrowingInitializer.class.getName(), - (t, p, ts) -> - Tuple.of(ThrowingInitializer.X, ThrowingInitializer.Y, ThrowingInitializer.X) - ); + factoryCache + .put( + ThrowingInitializer.class.getName(), + (t, p, ts) -> Tuple.of(ThrowingInitializer.X, ThrowingInitializer.Y, ThrowingInitializer.X)); vp = new VintageValueProvider(factoryCache, objenesis); // Should throw, because `giveRed` does instantiate objects: try { vp.giveRed(throwingInitializerTag); fail("Expected an exception"); - } catch (Error e) { + } + catch (Error e) { // succeed } } @@ -204,10 +202,9 @@ public AppendingStringTestFactory() { @Override public Tuple createValues( - TypeTag tag, - VintageValueProvider valueProvider, - LinkedHashSet typeStack - ) { + TypeTag tag, + VintageValueProvider valueProvider, + LinkedHashSet typeStack) { red += "r"; blue += "b"; return new Tuple<>(red, blue, new String(red)); @@ -220,10 +217,9 @@ private static final class ListTestFactory implements PrefabValueFactory { @Override @SuppressWarnings("unchecked") public Tuple createValues( - TypeTag tag, - VintageValueProvider valueProvider, - LinkedHashSet typeStack - ) { + TypeTag tag, + VintageValueProvider valueProvider, + LinkedHashSet typeStack) { TypeTag subtag = tag.getGenericTypes().get(0); List red = new ArrayList<>(); diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/AbstractGenericFactoryTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/AbstractGenericFactoryTest.java index 84d0d7e92..87875b512 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/AbstractGenericFactoryTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/AbstractGenericFactoryTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.LinkedHashSet; + import nl.jqno.equalsverifier.internal.exceptions.ReflectionException; import nl.jqno.equalsverifier.internal.instantiation.vintage.VintageValueProvider; import nl.jqno.equalsverifier.internal.reflection.Tuple; @@ -20,32 +21,22 @@ public class AbstractGenericFactoryTest { @BeforeEach public void setUp() { receiver = ""; - factory = - new AbstractGenericFactory() { - @Override - public Tuple createValues( + factory = new AbstractGenericFactory() { + @Override + public Tuple createValues( TypeTag tag, VintageValueProvider valueProvider, - LinkedHashSet typeStack - ) { - return Tuple.of("red", "blue", new String("red")); - } - }; + LinkedHashSet typeStack) { + return Tuple.of("red", "blue", new String("red")); + } + }; } @Test public void throwTheUnthrowableException() { assertThrows( ReflectionException.class, - () -> - factory.invoke( - String.class, - receiver, - "this method does not exist", - classes(), - objects() - ) - ); + () -> factory.invoke(String.class, receiver, "this method does not exist", classes(), objects())); } // The rest of this class is tested indirectly through its subclasses. } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/FallbackFactoryTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/FallbackFactoryTest.java index bb5d11a95..7868b77ca 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/FallbackFactoryTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/FallbackFactoryTest.java @@ -8,6 +8,7 @@ import static org.junit.jupiter.api.Assertions.assertNotSame; import java.util.LinkedHashSet; + import nl.jqno.equalsverifier.internal.exceptions.RecursionException; import nl.jqno.equalsverifier.internal.instantiation.vintage.FactoryCache; import nl.jqno.equalsverifier.internal.instantiation.vintage.VintageValueProvider; @@ -65,11 +66,7 @@ public void giveArray() { @Test public void giveClassWithFields() { - assertCorrectTuple( - IntContainer.class, - new IntContainer(42, 42), - new IntContainer(1337, 1337) - ); + assertCorrectTuple(IntContainer.class, new IntContainer(42, 42), new IntContainer(1337, 1337)); // Assert that static fields are untouched assertEquals(-100, IntContainer.staticI); assertEquals(-10, IntContainer.STATIC_FINAL_I); @@ -77,11 +74,7 @@ public void giveClassWithFields() { @Test public void redCopyIsNotSameAsRed() { - Tuple tuple = factory.createValues( - new TypeTag(IntContainer.class), - valueProvider, - typeStack - ); + Tuple tuple = factory.createValues(new TypeTag(IntContainer.class), valueProvider, typeStack); assertEquals(tuple.getRed(), tuple.getRedCopy()); assertNotSame(tuple.getRed(), tuple.getRedCopy()); @@ -90,26 +83,23 @@ public void redCopyIsNotSameAsRed() { @Test public void dontGiveRecursiveClass() { ExpectedException - .when(() -> factory.createValues(new TypeTag(Node.class), valueProvider, typeStack)) - .assertThrows(RecursionException.class); + .when(() -> factory.createValues(new TypeTag(Node.class), valueProvider, typeStack)) + .assertThrows(RecursionException.class); } @Test public void dontGiveTwoStepRecursiveClass() { ExpectedException - .when(() -> - factory.createValues(new TypeTag(TwoStepNodeA.class), valueProvider, typeStack) - ) - .assertThrows(RecursionException.class) - .assertDescriptionContains("TwoStepNodeA", "TwoStepNodeB"); + .when(() -> factory.createValues(new TypeTag(TwoStepNodeA.class), valueProvider, typeStack)) + .assertThrows(RecursionException.class) + .assertDescriptionContains("TwoStepNodeA", "TwoStepNodeB"); } @Test public void dontGiveRecursiveArray() { ExpectedException - .when(() -> factory.createValues(new TypeTag(NodeArray.class), valueProvider, typeStack) - ) - .assertThrows(RecursionException.class); + .when(() -> factory.createValues(new TypeTag(NodeArray.class), valueProvider, typeStack)) + .assertThrows(RecursionException.class); } private void assertCorrectTuple(Class type, T expectedRed, T expectedBlue) { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/MapFactoryTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/MapFactoryTest.java index da1f220e7..cfb057e71 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/MapFactoryTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/MapFactoryTest.java @@ -5,6 +5,7 @@ import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; + import nl.jqno.equalsverifier.internal.instantiation.JavaApiPrefabValues; import nl.jqno.equalsverifier.internal.instantiation.vintage.VintageValueProvider; import nl.jqno.equalsverifier.internal.reflection.Tuple; @@ -18,24 +19,13 @@ public class MapFactoryTest { private static final TypeTag STRING_TYPETAG = new TypeTag(String.class); - private static final TypeTag STRINGSTRINGMAP_TYPETAG = new TypeTag( - Map.class, - STRING_TYPETAG, - STRING_TYPETAG - ); + private static final TypeTag STRINGSTRINGMAP_TYPETAG = new TypeTag(Map.class, STRING_TYPETAG, STRING_TYPETAG); private static final TypeTag OBJECT_TYPETAG = new TypeTag(Object.class); - private static final TypeTag WILDCARDMAP_TYPETAG = new TypeTag( - Map.class, - OBJECT_TYPETAG, - OBJECT_TYPETAG - ); + private static final TypeTag WILDCARDMAP_TYPETAG = new TypeTag(Map.class, OBJECT_TYPETAG, OBJECT_TYPETAG); private static final TypeTag RAWMAP_TYPETAG = new TypeTag(Map.class); private static final TypeTag ONEELEMENTENUM_TYPETAG = new TypeTag(OneElementEnum.class); - private static final TypeTag ONEELEMENTENUMKEYMAP_TYPETAG = new TypeTag( - Map.class, - ONEELEMENTENUM_TYPETAG, - OBJECT_TYPETAG - ); + private static final TypeTag ONEELEMENTENUMKEYMAP_TYPETAG = + new TypeTag(Map.class, ONEELEMENTENUM_TYPETAG, OBJECT_TYPETAG); private static final MapFactory MAP_FACTORY = new MapFactory<>(HashMap::new); @@ -59,11 +49,7 @@ public void setUp() { @Test public void createMapsOfStringToString() { - Tuple tuple = MAP_FACTORY.createValues( - STRINGSTRINGMAP_TYPETAG, - valueProvider, - typeStack - ); + Tuple tuple = MAP_FACTORY.createValues(STRINGSTRINGMAP_TYPETAG, valueProvider, typeStack); assertEquals(mapOf(red, blue), tuple.getRed()); assertEquals(mapOf(blue, blue), tuple.getBlue()); } @@ -84,11 +70,7 @@ public void createRawMaps() { @Test public void createMapOfOneElementEnumKey() { - Tuple tuple = MAP_FACTORY.createValues( - ONEELEMENTENUMKEYMAP_TYPETAG, - valueProvider, - typeStack - ); + Tuple tuple = MAP_FACTORY.createValues(ONEELEMENTENUMKEYMAP_TYPETAG, valueProvider, typeStack); assertEquals(mapOf(redEnum, blueObject), tuple.getRed()); assertEquals(new HashMap<>(), tuple.getBlue()); } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/SimpleGenericFactoryTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/SimpleGenericFactoryTest.java index 7f7ba2b29..dbd5f3e5f 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/SimpleGenericFactoryTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factories/SimpleGenericFactoryTest.java @@ -4,6 +4,7 @@ import java.util.LinkedHashSet; import java.util.Optional; + import nl.jqno.equalsverifier.internal.instantiation.JavaApiPrefabValues; import nl.jqno.equalsverifier.internal.instantiation.vintage.VintageValueProvider; import nl.jqno.equalsverifier.internal.reflection.Tuple; @@ -19,25 +20,13 @@ public class SimpleGenericFactoryTest { private static final TypeTag STRING_TYPETAG = new TypeTag(String.class); private static final TypeTag INTEGER_TYPETAG = new TypeTag(Integer.class); private static final TypeTag OBJECT_TYPETAG = new TypeTag(Object.class); - private static final TypeTag STRINGOPTIONAL_TYPETAG = new TypeTag( - Optional.class, - STRING_TYPETAG - ); - private static final TypeTag WILDCARDOPTIONAL_TYPETAG = new TypeTag( - Optional.class, - OBJECT_TYPETAG - ); + private static final TypeTag STRINGOPTIONAL_TYPETAG = new TypeTag(Optional.class, STRING_TYPETAG); + private static final TypeTag WILDCARDOPTIONAL_TYPETAG = new TypeTag(Optional.class, OBJECT_TYPETAG); private static final TypeTag RAWOPTIONAL_TYPETAG = new TypeTag(Optional.class); - private static final TypeTag PAIR_TYPETAG = new TypeTag( - Pair.class, - STRING_TYPETAG, - INTEGER_TYPETAG - ); + private static final TypeTag PAIR_TYPETAG = new TypeTag(Pair.class, STRING_TYPETAG, INTEGER_TYPETAG); - private static final PrefabValueFactory OPTIONAL_FACTORY = Factories.simple( - Optional::of, - Optional::empty - ); + private static final PrefabValueFactory OPTIONAL_FACTORY = + Factories.simple(Optional::of, Optional::empty); private static final PrefabValueFactory PAIR_FACTORY = Factories.simple(Pair::new, null); private final LinkedHashSet typeStack = new LinkedHashSet<>(); @@ -62,33 +51,21 @@ public void setUp() { @Test public void createOptionalsOfMapOfString() { - Tuple tuple = OPTIONAL_FACTORY.createValues( - STRINGOPTIONAL_TYPETAG, - valueProvider, - typeStack - ); + Tuple tuple = OPTIONAL_FACTORY.createValues(STRINGOPTIONAL_TYPETAG, valueProvider, typeStack); assertEquals(Optional.of(redString), tuple.getRed()); assertEquals(Optional.of(blueString), tuple.getBlue()); } @Test public void createOptionalsOfWildcard() { - Tuple tuple = OPTIONAL_FACTORY.createValues( - WILDCARDOPTIONAL_TYPETAG, - valueProvider, - typeStack - ); + Tuple tuple = OPTIONAL_FACTORY.createValues(WILDCARDOPTIONAL_TYPETAG, valueProvider, typeStack); assertEquals(Optional.of(redObject), tuple.getRed()); assertEquals(Optional.of(blueObject), tuple.getBlue()); } @Test public void createRawOptionals() { - Tuple tuple = OPTIONAL_FACTORY.createValues( - RAWOPTIONAL_TYPETAG, - valueProvider, - typeStack - ); + Tuple tuple = OPTIONAL_FACTORY.createValues(RAWOPTIONAL_TYPETAG, valueProvider, typeStack); assertEquals(Optional.of(redObject), tuple.getRed()); assertEquals(Optional.of(blueObject), tuple.getBlue()); } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factoryproviders/JavaFxFactoryProviderTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factoryproviders/JavaFxFactoryProviderTest.java index ec5218593..7218ea8e5 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factoryproviders/JavaFxFactoryProviderTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/prefabvalues/factoryproviders/JavaFxFactoryProviderTest.java @@ -5,6 +5,7 @@ import java.util.List; import java.util.Map; + import nl.jqno.equalsverifier.internal.instantiation.JavaApiPrefabValues; import nl.jqno.equalsverifier.internal.instantiation.vintage.VintageValueProvider; import nl.jqno.equalsverifier.internal.instantiation.vintage.prefabvalues.factories.PrefabValueFactory; @@ -36,10 +37,8 @@ public void createInstancesWithCorrectSingleGenericParameter() { TypeTag tag = new TypeTag(GenericContainer.class, new TypeTag(String.class)); TypeTag listTag = new TypeTag(List.class, new TypeTag(String.class)); - PrefabValueFactory factory = new PropertyFactory<>( - GenericContainer.class.getName(), - List.class - ); + PrefabValueFactory factory = + new PropertyFactory<>(GenericContainer.class.getName(), List.class); Tuple tuple = factory.createValues(tag, valueProvider, null); assertEquals(valueProvider.giveRed(listTag), tuple.getRed().t); @@ -49,21 +48,11 @@ public void createInstancesWithCorrectSingleGenericParameter() { @Test public void createInstancesWithCorrectMultipleGenericParameter() { - TypeTag tag = new TypeTag( - GenericMultiContainer.class, - new TypeTag(String.class), - new TypeTag(Point.class) - ); - TypeTag mapTag = new TypeTag( - Map.class, - new TypeTag(String.class), - new TypeTag(Point.class) - ); - - PrefabValueFactory factory = new PropertyFactory<>( - GenericMultiContainer.class.getName(), - Map.class - ); + TypeTag tag = new TypeTag(GenericMultiContainer.class, new TypeTag(String.class), new TypeTag(Point.class)); + TypeTag mapTag = new TypeTag(Map.class, new TypeTag(String.class), new TypeTag(Point.class)); + + PrefabValueFactory factory = + new PropertyFactory<>(GenericMultiContainer.class.getName(), Map.class); Tuple tuple = factory.createValues(tag, valueProvider, null); assertEquals(valueProvider.giveRed(mapTag), tuple.getRed().t); diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/ClassAccessorTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/ClassAccessorTest.java index 912287180..74ea73491 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/ClassAccessorTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/ClassAccessorTest.java @@ -6,6 +6,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.LinkedHashSet; + import nl.jqno.equalsverifier.internal.instantiation.JavaApiPrefabValues; import nl.jqno.equalsverifier.internal.instantiation.vintage.FactoryCache; import nl.jqno.equalsverifier.internal.instantiation.vintage.VintageValueProvider; @@ -44,25 +45,17 @@ public void getRedObject() { @Test @SuppressWarnings("rawtypes") public void getRedObjectGeneric() { - ClassAccessor accessor = ClassAccessor.of( - GenericTypeVariableListContainer.class, - valueProvider, - objenesis - ); - GenericTypeVariableListContainer foo = accessor.getRedObject( - new TypeTag(GenericTypeVariableListContainer.class, new TypeTag(String.class)), - empty - ); + ClassAccessor accessor = + ClassAccessor.of(GenericTypeVariableListContainer.class, valueProvider, objenesis); + GenericTypeVariableListContainer foo = accessor + .getRedObject(new TypeTag(GenericTypeVariableListContainer.class, new TypeTag(String.class)), empty); assertEquals(String.class, foo.tList.get(0).getClass()); } @Test public void getRedAccessor() { PointContainer foo = pointContainerAccessor.getRedObject(TypeTag.NULL, empty); - ObjectAccessor objectAccessor = pointContainerAccessor.getRedAccessor( - TypeTag.NULL, - empty - ); + ObjectAccessor objectAccessor = pointContainerAccessor.getRedAccessor(TypeTag.NULL, empty); assertEquals(foo, objectAccessor.get()); } @@ -74,25 +67,17 @@ public void getBlueObject() { @Test @SuppressWarnings("rawtypes") public void getBlueObjectGeneric() { - ClassAccessor accessor = ClassAccessor.of( - GenericTypeVariableListContainer.class, - valueProvider, - objenesis - ); - GenericTypeVariableListContainer foo = accessor.getBlueObject( - new TypeTag(GenericTypeVariableListContainer.class, new TypeTag(String.class)), - empty - ); + ClassAccessor accessor = + ClassAccessor.of(GenericTypeVariableListContainer.class, valueProvider, objenesis); + GenericTypeVariableListContainer foo = accessor + .getBlueObject(new TypeTag(GenericTypeVariableListContainer.class, new TypeTag(String.class)), empty); assertEquals(String.class, foo.tList.get(0).getClass()); } @Test public void getBlueAccessor() { PointContainer foo = pointContainerAccessor.getBlueObject(TypeTag.NULL, empty); - ObjectAccessor objectAccessor = pointContainerAccessor.getBlueAccessor( - TypeTag.NULL, - empty - ); + ObjectAccessor objectAccessor = pointContainerAccessor.getBlueAccessor(TypeTag.NULL, empty); assertEquals(foo, objectAccessor.get()); } @@ -105,42 +90,29 @@ public void redAndBlueNotEqual() { @Test public void instantiateAllTypes() { - ClassAccessor - .of(AllTypesContainer.class, valueProvider, objenesis) - .getRedObject(TypeTag.NULL, empty); + ClassAccessor.of(AllTypesContainer.class, valueProvider, objenesis).getRedObject(TypeTag.NULL, empty); } @Test public void instantiateArrayTypes() { - ClassAccessor - .of(AllArrayTypesContainer.class, valueProvider, objenesis) - .getRedObject(TypeTag.NULL, empty); + ClassAccessor.of(AllArrayTypesContainer.class, valueProvider, objenesis).getRedObject(TypeTag.NULL, empty); } @Test public void instantiateRecursiveTypeUsingPrefabValue() { - factoryCache.put( - TwoStepNodeB.class, - values(new TwoStepNodeB(), new TwoStepNodeB(), new TwoStepNodeB()) - ); + factoryCache.put(TwoStepNodeB.class, values(new TwoStepNodeB(), new TwoStepNodeB(), new TwoStepNodeB())); valueProvider = new VintageValueProvider(factoryCache, objenesis); - ClassAccessor - .of(TwoStepNodeA.class, valueProvider, objenesis) - .getRedObject(TypeTag.NULL, empty); + ClassAccessor.of(TwoStepNodeA.class, valueProvider, objenesis).getRedObject(TypeTag.NULL, empty); } @Test public void instantiateInterfaceField() { - ClassAccessor - .of(InterfaceContainer.class, valueProvider, objenesis) - .getRedObject(TypeTag.NULL, empty); + ClassAccessor.of(InterfaceContainer.class, valueProvider, objenesis).getRedObject(TypeTag.NULL, empty); } @Test public void instantiateAbstractClassField() { - ClassAccessor - .of(AbstractClassContainer.class, valueProvider, objenesis) - .getRedObject(TypeTag.NULL, empty); + ClassAccessor.of(AbstractClassContainer.class, valueProvider, objenesis).getRedObject(TypeTag.NULL, empty); } @Test diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/FieldModifierTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/FieldModifierTest.java index 7746c1702..3602987ea 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/FieldModifierTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/FieldModifierTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertSame; import java.lang.reflect.Field; + import nl.jqno.equalsverifier.testhelpers.types.TypeHelper.ObjectContainer; import nl.jqno.equalsverifier.testhelpers.types.TypeHelper.PrimitiveContainer; import org.junit.jupiter.api.Test; @@ -46,7 +47,8 @@ private FieldModifier getAccessorFor(Object object, String fieldName) { try { Field field = object.getClass().getDeclaredField(fieldName); return FieldModifier.of(field, object); - } catch (NoSuchFieldException e) { + } + catch (NoSuchFieldException e) { throw new IllegalArgumentException("fieldName: " + fieldName); } } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/InPlaceObjectAccessorCopyingTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/InPlaceObjectAccessorCopyingTest.java index 5ec8b577a..babe31041 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/InPlaceObjectAccessorCopyingTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/instantiation/vintage/reflection/InPlaceObjectAccessorCopyingTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.lang.reflect.Field; + import nl.jqno.equalsverifier.internal.reflection.FieldIterable; import nl.jqno.equalsverifier.testhelpers.types.Point; import nl.jqno.equalsverifier.testhelpers.types.Point3D; @@ -77,7 +78,8 @@ private static void assertAllFieldsEqual(T original, T copy, Class doScramble(as)) - // InaccessibleObjectException, but it's not available in Java 8 - .assertThrows(RuntimeException.class) - .assertMessageContains("accessible: module", "does not \"opens"); + .when(() -> doScramble(as)) + // InaccessibleObjectException, but it's not available in Java 8 + .assertThrows(RuntimeException.class) + .assertMessageContains("accessible: module", "does not \"opens"); } @Test @@ -174,12 +175,8 @@ static final class FinalAssignedPointContainer { static final class GenericContainerContainer { - private final GenericContainer strings = new GenericContainer<>( - new ArrayList() - ); - private final GenericContainer points = new GenericContainer<>( - new ArrayList() - ); + private final GenericContainer strings = new GenericContainer<>(new ArrayList()); + private final GenericContainer points = new GenericContainer<>(new ArrayList()); } static final class GenericContainer { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/ConditionalInstantiatorTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/ConditionalInstantiatorTest.java index dea2d13ca..3100a9388 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/ConditionalInstantiatorTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/ConditionalInstantiatorTest.java @@ -13,6 +13,7 @@ import java.util.Collections; import java.util.GregorianCalendar; import java.util.List; + import nl.jqno.equalsverifier.internal.exceptions.ReflectionException; import org.junit.jupiter.api.Test; @@ -43,10 +44,7 @@ public void objectIsInstantiatedCorrectly_whenValidConstructorParametersAreProvi ci = new ConditionalInstantiator("java.util.GregorianCalendar"); Calendar expected = new GregorianCalendar(1999, 11, 31); - Calendar actual = ci.instantiate( - classes(int.class, int.class, int.class), - objects(1999, 11, 31) - ); + Calendar actual = ci.instantiate(classes(int.class, int.class, int.class), objects(1999, 11, 31)); assertThat(actual, is(expected)); } @@ -63,19 +61,14 @@ public void throwsIse_whenInvalidConstructorParametersAreProvided() { assertThrows( ReflectionException.class, - () -> - ci.instantiate(classes(int.class, int.class, int.class), objects(1999, 31, "hello")) - ); + () -> ci.instantiate(classes(int.class, int.class, int.class), objects(1999, 31, "hello"))); } @Test public void nullIsReturned_whenInvalidConstructorParametersAreProvided_givenFalse() { ci = new ConditionalInstantiator("java.util.GregorianCalendar", false); - Object actual = ci.instantiate( - classes(int.class, int.class, int.class), - objects(1999, 31, "hello") - ); + Object actual = ci.instantiate(classes(int.class, int.class, int.class), objects(1999, 31, "hello")); assertThat(actual, is(nullValue())); } @@ -101,8 +94,7 @@ public void throwsIse_whenInvalidMethodNameIsProvided() { assertThrows( ReflectionException.class, - () -> ci.callFactory("thisMethodDoesntExist", classes(int.class), objects(42)) - ); + () -> ci.callFactory("thisMethodDoesntExist", classes(int.class), objects(42))); } @Test @@ -119,8 +111,7 @@ public void throwsIse_whenInvalidFactoryMethodParametersAreProvided() { assertThrows( ReflectionException.class, - () -> ci.callFactory("valueOf", classes(int.class, int.class), objects(42)) - ); + () -> ci.callFactory("valueOf", classes(int.class, int.class), objects(42))); } @Test @@ -153,21 +144,14 @@ public void throwsIse_whenExternalFactoryIsCalled_givenFactoryTypeDoesNotExist() assertThrows( ReflectionException.class, - () -> - ci.callFactory("java.util.ThisTypeDoesNotExist", "emptyList", classes(), objects()) - ); + () -> ci.callFactory("java.util.ThisTypeDoesNotExist", "emptyList", classes(), objects())); } @Test public void nullIsReturned_whenExternalFactoryIsCalled_givenFactoryTypeDoesNotExist_givenFalse() { ci = new ConditionalInstantiator("java.util.List", false); - Object actual = ci.callFactory( - "java.util.ThisTypeDoesNotExist", - "emptyList", - classes(), - objects() - ); + Object actual = ci.callFactory("java.util.ThisTypeDoesNotExist", "emptyList", classes(), objects()); assertThat(actual, is(nullValue())); } @@ -177,26 +161,14 @@ public void throwsIse_whenInvalidExternalFactoryMethodNameIsProvided() { assertThrows( ReflectionException.class, - () -> - ci.callFactory( - "java.util.Collections", - "thisMethodDoesntExist", - classes(), - objects() - ) - ); + () -> ci.callFactory("java.util.Collections", "thisMethodDoesntExist", classes(), objects())); } @Test public void nullIsReturned_whenInvalidExternalFactoryMethodNameIsProvided_givenFalse() { ci = new ConditionalInstantiator("java.util.List", false); - Object actual = ci.callFactory( - "java.util.Collections", - "thisMethodDoesntExist", - classes(), - objects() - ); + Object actual = ci.callFactory("java.util.Collections", "thisMethodDoesntExist", classes(), objects()); assertThat(actual, is(nullValue())); } @@ -206,26 +178,14 @@ public void throwsIse_whenInvalidExternalFactoryMethodParametersAreProvided() { assertThrows( ReflectionException.class, - () -> - ci.callFactory( - "java.util.Collections", - "emptyList", - classes(int.class), - objects(42) - ) - ); + () -> ci.callFactory("java.util.Collections", "emptyList", classes(int.class), objects(42))); } @Test public void nullIsReturned_whenInvalidExternalFactoryMethodParametersAreProvided_givenFalse() { ci = new ConditionalInstantiator("java.util.List", false); - Object actual = ci.callFactory( - "java.util.Collections", - "emptyList", - classes(int.class), - objects(42) - ); + Object actual = ci.callFactory("java.util.Collections", "emptyList", classes(int.class), objects(42)); assertThat(actual, is(nullValue())); } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/FieldCacheTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/FieldCacheTest.java index 5d09df19a..95b842783 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/FieldCacheTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/FieldCacheTest.java @@ -5,6 +5,7 @@ import java.util.Collections; import java.util.HashSet; import java.util.Set; + import org.junit.jupiter.api.Test; public class FieldCacheTest { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/FieldIterableTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/FieldIterableTest.java index 9578cf0fb..fb8fda7c7 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/FieldIterableTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/FieldIterableTest.java @@ -6,17 +6,16 @@ import java.lang.reflect.Field; import java.util.*; + import nl.jqno.equalsverifier.testhelpers.types.TypeHelper.*; import org.junit.jupiter.api.Test; public class FieldIterableTest { private static final Set FIELD_CONTAINER_FIELDS = createFieldContainerFields(); - private static final Set NONSTATIC_FIELD_CONTAINER_FIELDS = - createNonStaticFieldContainerFields(); + private static final Set NONSTATIC_FIELD_CONTAINER_FIELDS = createNonStaticFieldContainerFields(); private static final Set SUB_FIELD_CONTAINER_FIELDS = createSubFieldContainerFields(); - private static final Set FIELD_AND_SUB_FIELD_CONTAINER_FIELDS = - createFieldAndSubFieldContainerFields(); + private static final Set FIELD_AND_SUB_FIELD_CONTAINER_FIELDS = createFieldAndSubFieldContainerFields(); @Test public void simpleFields() { @@ -31,9 +30,7 @@ public void simpleFields() { @Test public void simpleFieldsWithoutStatics() { Set actual = new HashSet<>(); - for (Field field : FieldIterable.ofIgnoringStatic( - DifferentAccessModifiersFieldContainer.class - )) { + for (Field field : FieldIterable.ofIgnoringStatic(DifferentAccessModifiersFieldContainer.class)) { actual.add(field); } @@ -53,9 +50,7 @@ public void subAndSuperClassFields() { @Test public void onlySubClassFields() { Set actual = new HashSet<>(); - for (Field field : FieldIterable.ofIgnoringSuper( - DifferentAccessModifiersSubFieldContainer.class - )) { + for (Field field : FieldIterable.ofIgnoringSuper(DifferentAccessModifiersSubFieldContainer.class)) { actual.add(field); } @@ -124,9 +119,7 @@ public void interfaceTest() { @Test public void nextAfterLastElement() { - Iterator iterator = FieldIterable - .of(DifferentAccessModifiersFieldContainer.class) - .iterator(); + Iterator iterator = FieldIterable.of(DifferentAccessModifiersFieldContainer.class).iterator(); while (iterator.hasNext()) { iterator.next(); } @@ -159,8 +152,7 @@ public void ignoreNonSyntheticCoberturaFields() { private static Set createFieldContainerFields() { Set result = new HashSet<>(); - Class type = - DifferentAccessModifiersFieldContainer.class; + Class type = DifferentAccessModifiersFieldContainer.class; try { result.add(type.getDeclaredField("i")); result.add(type.getDeclaredField("j")); @@ -170,7 +162,8 @@ private static Set createFieldContainerFields() { result.add(type.getDeclaredField("J")); result.add(type.getDeclaredField("K")); result.add(type.getDeclaredField("L")); - } catch (NoSuchFieldException e) { + } + catch (NoSuchFieldException e) { throw new IllegalStateException(e); } return result; @@ -178,14 +171,14 @@ private static Set createFieldContainerFields() { private static Set createNonStaticFieldContainerFields() { Set result = new HashSet<>(); - Class type = - DifferentAccessModifiersFieldContainer.class; + Class type = DifferentAccessModifiersFieldContainer.class; try { result.add(type.getDeclaredField("i")); result.add(type.getDeclaredField("j")); result.add(type.getDeclaredField("k")); result.add(type.getDeclaredField("l")); - } catch (NoSuchFieldException e) { + } + catch (NoSuchFieldException e) { throw new IllegalStateException(e); } return result; @@ -193,14 +186,14 @@ private static Set createNonStaticFieldContainerFields() { private static Set createSubFieldContainerFields() { Set result = new HashSet<>(); - Class type = - DifferentAccessModifiersSubFieldContainer.class; + Class type = DifferentAccessModifiersSubFieldContainer.class; try { result.add(type.getDeclaredField("a")); result.add(type.getDeclaredField("b")); result.add(type.getDeclaredField("c")); result.add(type.getDeclaredField("d")); - } catch (NoSuchFieldException e) { + } + catch (NoSuchFieldException e) { throw new IllegalStateException(e); } return result; diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/FieldProbeTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/FieldProbeTest.java index c7f23c7a1..c5abbe307 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/FieldProbeTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/FieldProbeTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.*; import java.lang.reflect.Field; + import nl.jqno.equalsverifier.internal.util.Configuration; import nl.jqno.equalsverifier.internal.util.ConfigurationHelper; import nl.jqno.equalsverifier.testhelpers.types.TypeHelper.*; @@ -122,33 +123,21 @@ public void canBeDefault_primitive() { @Test public void canBeDefault_primitiveWithPrefabbedField() { - config = - ConfigurationHelper.emptyConfigurationWithPrefabbedFields( - PrimitiveContainer.class, - FIELD_NAME - ); + config = ConfigurationHelper.emptyConfigurationWithPrefabbedFields(PrimitiveContainer.class, FIELD_NAME); FieldProbe probe = getProbeFor(PrimitiveContainer.class, FIELD_NAME); assertFalse(probe.canBeDefault(config)); } @Test public void canBeDefault_isMentionedExplicitly() { - config = - ConfigurationHelper.emptyConfigurationWithNonnullFields( - ObjectContainer.class, - FIELD_NAME - ); + config = ConfigurationHelper.emptyConfigurationWithNonnullFields(ObjectContainer.class, FIELD_NAME); FieldProbe probe = getProbeFor(ObjectContainer.class, FIELD_NAME); assertFalse(probe.canBeDefault(config)); } @Test public void canBeDefault_annotated() { - config = - ConfigurationHelper.emptyConfigurationWithNonnullFields( - NonNullContainer.class, - FIELD_NAME - ); + config = ConfigurationHelper.emptyConfigurationWithNonnullFields(NonNullContainer.class, FIELD_NAME); FieldProbe probe = getProbeFor(NonNullContainer.class, FIELD_NAME); assertFalse(probe.canBeDefault(config)); } @@ -187,7 +176,8 @@ private FieldProbe getProbeFor(Class type, String fieldName) { try { Field field = type.getDeclaredField(fieldName); return FieldProbe.of(field); - } catch (NoSuchFieldException e) { + } + catch (NoSuchFieldException e) { throw new IllegalArgumentException("fieldName: " + fieldName); } } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/InstantiatorTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/InstantiatorTest.java index be7a5357a..18b0d5042 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/InstantiatorTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/InstantiatorTest.java @@ -7,6 +7,7 @@ import java.lang.reflect.Field; import java.util.List; + import net.bytebuddy.ByteBuddy; import net.bytebuddy.description.modifier.Visibility; import net.bytebuddy.dynamic.scaffold.TypeValidation; @@ -34,9 +35,7 @@ public void instantiateClass() { @Test public void fieldsOfInstantiatedObjectHaveDefaultValues() { - ColorBlindColorPoint p = Instantiator - .of(ColorBlindColorPoint.class, objenesis) - .instantiate(); + ColorBlindColorPoint p = Instantiator.of(ColorBlindColorPoint.class, objenesis).instantiate(); assertEquals(0, p.x); assertEquals(null, p.color); } @@ -104,11 +103,11 @@ public void instantiateTheSameSubclass() { @Test public void giveDynamicSubclass() throws Exception { class Super {} - Class sub = Instantiator.giveDynamicSubclass( - Super.class, - "dynamicField", - b -> b.defineField("dynamicField", int.class, Visibility.PRIVATE) - ); + Class sub = Instantiator + .giveDynamicSubclass( + Super.class, + "dynamicField", + b -> b.defineField("dynamicField", int.class, Visibility.PRIVATE)); Field f = sub.getDeclaredField("dynamicField"); assertNotNull(f); } @@ -116,12 +115,12 @@ class Super {} @Test public void giveDynamicSubclassForClassWithNoPackage() { Class type = new ByteBuddy() - .with(TypeValidation.DISABLED) - .subclass(Object.class) - .name("NoPackage") - .make() - .load(getClass().getClassLoader()) - .getLoaded(); + .with(TypeValidation.DISABLED) + .subclass(Object.class) + .name("NoPackage") + .make() + .load(getClass().getClassLoader()) + .getLoaded(); Instantiator.giveDynamicSubclass(type, "X", b -> b); } } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/PackageScannerTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/PackageScannerTest.java index ba33ed158..87a3ae6d6 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/PackageScannerTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/PackageScannerTest.java @@ -9,6 +9,7 @@ import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; + import nl.jqno.equalsverifier.testhelpers.packages.correct.A; import nl.jqno.equalsverifier.testhelpers.packages.correct.B; import nl.jqno.equalsverifier.testhelpers.packages.correct.C; @@ -30,135 +31,91 @@ public void coverTheConstructor() { @Test public void happyPath() { - List> classes = PackageScanner.getClassesIn( - "nl.jqno.equalsverifier.testhelpers.packages.correct", - null, - false - ); + List> classes = + PackageScanner.getClassesIn("nl.jqno.equalsverifier.testhelpers.packages.correct", null, false); sort(classes); assertEquals(Arrays.asList(A.class, B.class, C.class), classes); } @Test public void happyPathMustExtendClass() { - List> classes = PackageScanner.getClassesIn( - "nl.jqno.equalsverifier.testhelpers.packages.subclasses", - SuperA.class, - false - ); + List> classes = PackageScanner + .getClassesIn("nl.jqno.equalsverifier.testhelpers.packages.subclasses", SuperA.class, false); sort(classes); assertEquals(Arrays.asList(SubA1.class, SubA2.class), classes); } @Test public void happyPathMustExtendInterface() { - List> classes = PackageScanner.getClassesIn( - "nl.jqno.equalsverifier.testhelpers.packages.subclasses", - SuperI.class, - false - ); + List> classes = PackageScanner + .getClassesIn("nl.jqno.equalsverifier.testhelpers.packages.subclasses", SuperI.class, false); sort(classes); assertEquals(Arrays.asList(SubI1.class, SubI2.class), classes); } @Test public void happyPathRecursive() { - List> classes = PackageScanner.getClassesIn( - "nl.jqno.equalsverifier.testhelpers.packages.correct", - null, - true - ); + List> classes = + PackageScanner.getClassesIn("nl.jqno.equalsverifier.testhelpers.packages.correct", null, true); sort(classes); assertEquals( - Arrays.asList( - A.class, - B.class, - C.class, - nl.jqno.equalsverifier.testhelpers.packages.correct.subpackage.A.class, - nl.jqno.equalsverifier.testhelpers.packages.correct.subpackage.B.class, - nl.jqno.equalsverifier.testhelpers.packages.correct.subpackage.subpackage.A.class, - nl.jqno.equalsverifier.testhelpers.packages.correct.subpackage.subpackage.B.class, - nl.jqno.equalsverifier.testhelpers.packages.correct.subpackage.subpackage.D.class - ), - classes - ); + Arrays + .asList( + A.class, + B.class, + C.class, + nl.jqno.equalsverifier.testhelpers.packages.correct.subpackage.A.class, + nl.jqno.equalsverifier.testhelpers.packages.correct.subpackage.B.class, + nl.jqno.equalsverifier.testhelpers.packages.correct.subpackage.subpackage.A.class, + nl.jqno.equalsverifier.testhelpers.packages.correct.subpackage.subpackage.B.class, + nl.jqno.equalsverifier.testhelpers.packages.correct.subpackage.subpackage.D.class), + classes); } @Test public void happyPathMustExtendClassRecursive() { - List> classes = PackageScanner.getClassesIn( - "nl.jqno.equalsverifier.testhelpers.packages.subclasses", - SuperA.class, - true - ); + List> classes = PackageScanner + .getClassesIn("nl.jqno.equalsverifier.testhelpers.packages.subclasses", SuperA.class, true); sort(classes); assertEquals(Arrays.asList(SubA1.class, SubA2.class, SubA3.class), classes); } @Test public void filterOutTestClasses() { - List> classes = PackageScanner.getClassesIn( - "nl.jqno.equalsverifier.internal.reflection", - null, - false - ); - List> testClasses = classes - .stream() - .filter(c -> c.getName().endsWith("Test")) - .collect(Collectors.toList()); + List> classes = PackageScanner.getClassesIn("nl.jqno.equalsverifier.internal.reflection", null, false); + List> testClasses = + classes.stream().filter(c -> c.getName().endsWith("Test")).collect(Collectors.toList()); assertEquals(Collections.emptyList(), testClasses); assertTrue(classes.size() - testClasses.size() > 0); } @Test public void filterOutTestClassesRecursively() { - List> classes = PackageScanner.getClassesIn( - "nl.jqno.equalsverifier.internal.reflection", - null, - true - ); - List> testClasses = classes - .stream() - .filter(c -> c.getName().endsWith("Test")) - .collect(Collectors.toList()); + List> classes = PackageScanner.getClassesIn("nl.jqno.equalsverifier.internal.reflection", null, true); + List> testClasses = + classes.stream().filter(c -> c.getName().endsWith("Test")).collect(Collectors.toList()); assertEquals(Collections.emptyList(), testClasses); assertTrue(classes.size() - testClasses.size() > 0); } @Test public void nonexistentPackage() { - List> classes = PackageScanner.getClassesIn( - "nl.jqno.equalsverifier.nonexistentpackage", - null, - false - ); + List> classes = PackageScanner.getClassesIn("nl.jqno.equalsverifier.nonexistentpackage", null, false); assertEquals(Collections.emptyList(), classes); } @Test public void nonexistentPackageAndSubPackage() { - List> classes = PackageScanner.getClassesIn( - "nl.jqno.equalsverifier.nonexistentpackage", - null, - true - ); + List> classes = PackageScanner.getClassesIn("nl.jqno.equalsverifier.nonexistentpackage", null, true); assertEquals(Collections.emptyList(), classes); } @Test public void anonymousAndLocalClassesAreSkipped() { - List> classes = PackageScanner.getClassesIn( - "nl.jqno.equalsverifier.testhelpers.packages.anonymous", - null, - false - ); + List> classes = + PackageScanner.getClassesIn("nl.jqno.equalsverifier.testhelpers.packages.anonymous", null, false); - assertEquals( - Collections.singletonList( - nl.jqno.equalsverifier.testhelpers.packages.anonymous.A.class - ), - classes - ); + assertEquals(Collections.singletonList(nl.jqno.equalsverifier.testhelpers.packages.anonymous.A.class), classes); } private void sort(List> classes) { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/SuperclassIterableTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/SuperclassIterableTest.java index 71a3629e3..2fa1a6199 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/SuperclassIterableTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/SuperclassIterableTest.java @@ -7,6 +7,7 @@ import java.util.ArrayList; import java.util.List; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -48,10 +49,7 @@ public void hierarchyIncludeSelf() { for (Class type : SuperclassIterable.ofIncludeSelf(SimpleSubSubclass.class)) { actual.add(type); } - assertEquals( - asList(SimpleSubSubclass.class, SimpleSubclass.class, SimpleClass.class), - actual - ); + assertEquals(asList(SimpleSubSubclass.class, SimpleSubclass.class, SimpleClass.class), actual); } @Test diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/TypeTagParameterizedTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/TypeTagParameterizedTest.java index 424ecef38..7b73b25fc 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/TypeTagParameterizedTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/TypeTagParameterizedTest.java @@ -7,6 +7,7 @@ import java.util.List; import java.util.Map; import java.util.stream.Stream; + import nl.jqno.equalsverifier.testhelpers.types.Point; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -27,10 +28,7 @@ public class TypeTagParameterizedTest { private final Map> fieldWithNestedTypeParameters = null; @SuppressWarnings("unused") - private final Map< - List, - Map, Map> - > fieldWithRidiculousTypeParameters = null; + private final Map, Map, Map>> fieldWithRidiculousTypeParameters = null; @SuppressWarnings({ "unused", "rawtypes" }) private final Map rawMapField = null; @@ -60,65 +58,49 @@ public class TypeTagParameterizedTest { private final String[] arrayField = null; private static Stream data() { - return Stream.of( - Arguments.of("simpleField", new TypeTag(String.class)), - Arguments.of( - "fieldWithSingleTypeParameter", - new TypeTag(List.class, new TypeTag(String.class)) - ), - Arguments.of( - "fieldWithTwoTypeParameters", - new TypeTag(Map.class, new TypeTag(String.class), new TypeTag(Integer.class)) - ), - Arguments.of( - "fieldWithNestedTypeParameters", - new TypeTag( - Map.class, - new TypeTag(String.class), - new TypeTag(List.class, new TypeTag(String.class)) - ) - ), - Arguments.of( - "fieldWithRidiculousTypeParameters", - new TypeTag( - Map.class, - new TypeTag(List.class, new TypeTag(Integer.class)), - new TypeTag( - Map.class, - new TypeTag(List.class, new TypeTag(Double.class)), - new TypeTag(Map.class, new TypeTag(String.class), new TypeTag(Float.class)) - ) - ) - ), - Arguments.of("rawMapField", new TypeTag(Map.class)), - Arguments.of( - "fieldWithWildcardParameter", - new TypeTag(List.class, new TypeTag(Object.class)) - ), - Arguments.of( - "fieldWithExtendingWildcardWithTypeVariable", - new TypeTag(List.class, new TypeTag(Comparable.class, new TypeTag(Object.class))) - ), - Arguments.of( - "fieldWithExtendingWildcardWithWildcard", - new TypeTag(List.class, new TypeTag(Comparable.class, new TypeTag(Object.class))) - ), - Arguments.of( - "fieldWithSuperingWildcard", - new TypeTag(List.class, new TypeTag(Point.class)) - ), - Arguments.of( - "fieldWithGenericArrayParameter", - new TypeTag(Class[].class, new TypeTag(String.class)) - ), - Arguments.of( - "fieldWithTypeVariable", - new TypeTag(List.class, new TypeTag(Object.class)) - ), - // See TypeTagTest for fieldWithBoundedTypeVariable - Arguments.of("primitiveField", new TypeTag(int.class)), - Arguments.of("arrayField", new TypeTag(String[].class)) - ); + return Stream + .of( + Arguments.of("simpleField", new TypeTag(String.class)), + Arguments.of("fieldWithSingleTypeParameter", new TypeTag(List.class, new TypeTag(String.class))), + Arguments + .of( + "fieldWithTwoTypeParameters", + new TypeTag(Map.class, new TypeTag(String.class), new TypeTag(Integer.class))), + Arguments + .of( + "fieldWithNestedTypeParameters", + new TypeTag(Map.class, + new TypeTag(String.class), + new TypeTag(List.class, new TypeTag(String.class)))), + Arguments + .of( + "fieldWithRidiculousTypeParameters", + new TypeTag(Map.class, + new TypeTag(List.class, new TypeTag(Integer.class)), + new TypeTag(Map.class, + new TypeTag(List.class, new TypeTag(Double.class)), + new TypeTag(Map.class, + new TypeTag(String.class), + new TypeTag(Float.class))))), + Arguments.of("rawMapField", new TypeTag(Map.class)), + Arguments.of("fieldWithWildcardParameter", new TypeTag(List.class, new TypeTag(Object.class))), + Arguments + .of( + "fieldWithExtendingWildcardWithTypeVariable", + new TypeTag(List.class, new TypeTag(Comparable.class, new TypeTag(Object.class)))), + Arguments + .of( + "fieldWithExtendingWildcardWithWildcard", + new TypeTag(List.class, new TypeTag(Comparable.class, new TypeTag(Object.class)))), + Arguments.of("fieldWithSuperingWildcard", new TypeTag(List.class, new TypeTag(Point.class))), + Arguments + .of( + "fieldWithGenericArrayParameter", + new TypeTag(Class[].class, new TypeTag(String.class))), + Arguments.of("fieldWithTypeVariable", new TypeTag(List.class, new TypeTag(Object.class))), + // See TypeTagTest for fieldWithBoundedTypeVariable + Arguments.of("primitiveField", new TypeTag(int.class)), + Arguments.of("arrayField", new TypeTag(String[].class))); } @ParameterizedTest @@ -131,7 +113,8 @@ public void correctness(String fieldName, TypeTag expected) { private Field getField(String name) { try { return getClass().getDeclaredField(name); - } catch (NoSuchFieldException e) { + } + catch (NoSuchFieldException e) { fail(e.toString()); return null; } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/TypeTagTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/TypeTagTest.java index f74a6cc5a..dbd85cd10 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/TypeTagTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/TypeTagTest.java @@ -7,6 +7,7 @@ import java.util.Arrays; import java.util.List; import java.util.Map; + import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; import nl.jqno.equalsverifier.testhelpers.types.Point; @@ -14,19 +15,16 @@ public class TypeTagTest { - private static final TypeTag SOME_LONG_TYPETAG = new TypeTag( - Map.class, - new TypeTag(Integer.class), - new TypeTag(List.class, new TypeTag(String.class)) - ); + private static final TypeTag SOME_LONG_TYPETAG = + new TypeTag(Map.class, new TypeTag(Integer.class), new TypeTag(List.class, new TypeTag(String.class))); @Test public void equalsAndHashCode() { EqualsVerifier - .forClass(TypeTag.class) - .withPrefabValues(TypeTag.class, new TypeTag(Integer.class), SOME_LONG_TYPETAG) - .suppress(Warning.NULL_FIELDS) - .verify(); + .forClass(TypeTag.class) + .withPrefabValues(TypeTag.class, new TypeTag(Integer.class), SOME_LONG_TYPETAG) + .suppress(Warning.NULL_FIELDS) + .verify(); } @Test @@ -41,10 +39,8 @@ public void getType() { @Test public void getGenericTypes() { - List expected = Arrays.asList( - new TypeTag(Integer.class), - new TypeTag(List.class, new TypeTag(String.class)) - ); + List expected = + Arrays.asList(new TypeTag(Integer.class), new TypeTag(List.class, new TypeTag(String.class))); assertEquals(expected, SOME_LONG_TYPETAG.getGenericTypes()); } @@ -96,10 +92,7 @@ public void matchNestedParameterizedGenericField() throws Exception { Field f = Container.class.getDeclaredField("tss"); TypeTag actual = TypeTag.of(f, enclosingType); - assertEquals( - new TypeTag(List.class, new TypeTag(List.class, new TypeTag(String.class))), - actual - ); + assertEquals(new TypeTag(List.class, new TypeTag(List.class, new TypeTag(String.class))), actual); } @Test @@ -112,8 +105,7 @@ public void correctnessOfBoundedTypeVariable() throws NoSuchFieldException { @Test public void correctnessOfRecursiveBoundedTypeVariable() throws NoSuchFieldException { - Field field = - RecursiveBoundedTypeVariable.class.getDeclaredField("fieldWithBoundedTypeVariable"); + Field field = RecursiveBoundedTypeVariable.class.getDeclaredField("fieldWithBoundedTypeVariable"); TypeTag expected = new TypeTag(Comparable.class, new TypeTag(Object.class)); TypeTag actual = TypeTag.of(field, TypeTag.NULL); assertEquals(expected, actual); @@ -121,10 +113,7 @@ public void correctnessOfRecursiveBoundedTypeVariable() throws NoSuchFieldExcept @Test public void correctnessOfRecursiveBoundedWildcardTypeVariable() throws NoSuchFieldException { - Field field = - RecursiveBoundedWildcardTypeVariable.class.getDeclaredField( - "fieldWithBoundedTypeVariable" - ); + Field field = RecursiveBoundedWildcardTypeVariable.class.getDeclaredField("fieldWithBoundedTypeVariable"); TypeTag expected = new TypeTag(Comparable.class, new TypeTag(Object.class)); TypeTag actual = TypeTag.of(field, TypeTag.NULL); assertEquals(expected, actual); diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/UtilTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/UtilTest.java index 79f0eacfa..1859f14a7 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/UtilTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/UtilTest.java @@ -7,6 +7,7 @@ import java.util.GregorianCalendar; import java.util.HashSet; import java.util.Set; + import nl.jqno.equalsverifier.testhelpers.types.Point; import org.junit.jupiter.api.Test; diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/annotations/AnnotationCacheBuilderTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/annotations/AnnotationCacheBuilderTest.java index 6eb8fcce7..f892fe396 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/annotations/AnnotationCacheBuilderTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/annotations/AnnotationCacheBuilderTest.java @@ -9,6 +9,7 @@ import java.util.HashSet; import java.util.Set; import javax.annotation.Nonnull; + import net.bytebuddy.description.modifier.Visibility; import nl.jqno.equalsverifier.internal.reflection.Instantiator; import nl.jqno.equalsverifier.internal.reflection.Util; @@ -37,18 +38,12 @@ public class AnnotationCacheBuilderTest { @BeforeEach public void setUp() { cache = new AnnotationCache(); - cacheBuilder = - new AnnotationCacheBuilder(TestSupportedAnnotations.values(), NO_INGORED_ANNOTATIONS); + cacheBuilder = new AnnotationCacheBuilder(TestSupportedAnnotations.values(), NO_INGORED_ANNOTATIONS); } @Test public void findRuntimeAnnotationInType() { - build( - AnnotatedWithRuntime.class, - AnnotatedWithClass.class, - AnnotatedWithBoth.class, - AnnotatedFields.class - ); + build(AnnotatedWithRuntime.class, AnnotatedWithClass.class, AnnotatedWithBoth.class, AnnotatedFields.class); assertTypeHasAnnotation(AnnotatedWithRuntime.class, TYPE_RUNTIME_RETENTION); assertTypeHasAnnotation(AnnotatedWithBoth.class, TYPE_RUNTIME_RETENTION); @@ -58,12 +53,7 @@ public void findRuntimeAnnotationInType() { @Test public void findClassAnnotationInType() { - build( - AnnotatedWithRuntime.class, - AnnotatedWithClass.class, - AnnotatedWithBoth.class, - AnnotatedFields.class - ); + build(AnnotatedWithRuntime.class, AnnotatedWithClass.class, AnnotatedWithBoth.class, AnnotatedFields.class); assertTypeHasAnnotation(AnnotatedWithClass.class, TYPE_CLASS_RETENTION); assertTypeHasAnnotation(AnnotatedWithBoth.class, TYPE_CLASS_RETENTION); @@ -77,16 +67,8 @@ public void findRuntimeAnnotationInField() { assertFieldHasAnnotation(AnnotatedFields.class, RUNTIME_RETENTION, FIELD_RUNTIME_RETENTION); assertFieldHasAnnotation(AnnotatedFields.class, BOTH_RETENTIONS, FIELD_RUNTIME_RETENTION); - assertFieldDoesNotHaveAnnotation( - AnnotatedFields.class, - CLASS_RETENTION, - FIELD_RUNTIME_RETENTION - ); - assertFieldDoesNotHaveAnnotation( - AnnotatedFields.class, - NO_RETENTION, - FIELD_RUNTIME_RETENTION - ); + assertFieldDoesNotHaveAnnotation(AnnotatedFields.class, CLASS_RETENTION, FIELD_RUNTIME_RETENTION); + assertFieldDoesNotHaveAnnotation(AnnotatedFields.class, NO_RETENTION, FIELD_RUNTIME_RETENTION); } @Test @@ -95,38 +77,18 @@ public void findClassAnnotationInField() { assertFieldHasAnnotation(AnnotatedFields.class, CLASS_RETENTION, FIELD_CLASS_RETENTION); assertFieldHasAnnotation(AnnotatedFields.class, BOTH_RETENTIONS, FIELD_CLASS_RETENTION); - assertFieldDoesNotHaveAnnotation( - AnnotatedFields.class, - RUNTIME_RETENTION, - FIELD_CLASS_RETENTION - ); - assertFieldDoesNotHaveAnnotation( - AnnotatedFields.class, - NO_RETENTION, - FIELD_CLASS_RETENTION - ); + assertFieldDoesNotHaveAnnotation(AnnotatedFields.class, RUNTIME_RETENTION, FIELD_CLASS_RETENTION); + assertFieldDoesNotHaveAnnotation(AnnotatedFields.class, NO_RETENTION, FIELD_CLASS_RETENTION); } @Test public void findTypeUseRuntimeAnnotationInField() { build(AnnotatedTypes.class); - assertFieldHasAnnotation( - AnnotatedTypes.class, - RUNTIME_RETENTION, - TYPEUSE_RUNTIME_RETENTION - ); + assertFieldHasAnnotation(AnnotatedTypes.class, RUNTIME_RETENTION, TYPEUSE_RUNTIME_RETENTION); assertFieldHasAnnotation(AnnotatedTypes.class, BOTH_RETENTIONS, TYPEUSE_RUNTIME_RETENTION); - assertFieldDoesNotHaveAnnotation( - AnnotatedTypes.class, - CLASS_RETENTION, - TYPEUSE_RUNTIME_RETENTION - ); - assertFieldDoesNotHaveAnnotation( - AnnotatedTypes.class, - NO_RETENTION, - TYPEUSE_RUNTIME_RETENTION - ); + assertFieldDoesNotHaveAnnotation(AnnotatedTypes.class, CLASS_RETENTION, TYPEUSE_RUNTIME_RETENTION); + assertFieldDoesNotHaveAnnotation(AnnotatedTypes.class, NO_RETENTION, TYPEUSE_RUNTIME_RETENTION); } @Test @@ -135,38 +97,18 @@ public void findTypeUseClassAnnotationInField() { assertFieldHasAnnotation(AnnotatedTypes.class, CLASS_RETENTION, TYPEUSE_CLASS_RETENTION); assertFieldHasAnnotation(AnnotatedTypes.class, BOTH_RETENTIONS, TYPEUSE_CLASS_RETENTION); - assertFieldDoesNotHaveAnnotation( - AnnotatedTypes.class, - RUNTIME_RETENTION, - TYPEUSE_CLASS_RETENTION - ); - assertFieldDoesNotHaveAnnotation( - AnnotatedTypes.class, - NO_RETENTION, - TYPEUSE_CLASS_RETENTION - ); + assertFieldDoesNotHaveAnnotation(AnnotatedTypes.class, RUNTIME_RETENTION, TYPEUSE_CLASS_RETENTION); + assertFieldDoesNotHaveAnnotation(AnnotatedTypes.class, NO_RETENTION, TYPEUSE_CLASS_RETENTION); } @Test public void findRuntimeAnnotationInMethod() { build(AnnotatedMethods.class); - assertFieldHasAnnotation( - AnnotatedMethods.class, - RUNTIME_RETENTION, - METHOD_RUNTIME_RETENTION - ); + assertFieldHasAnnotation(AnnotatedMethods.class, RUNTIME_RETENTION, METHOD_RUNTIME_RETENTION); assertFieldHasAnnotation(AnnotatedMethods.class, BOTH_RETENTIONS, METHOD_RUNTIME_RETENTION); - assertFieldDoesNotHaveAnnotation( - AnnotatedMethods.class, - CLASS_RETENTION, - METHOD_RUNTIME_RETENTION - ); - assertFieldDoesNotHaveAnnotation( - AnnotatedMethods.class, - NO_RETENTION, - METHOD_RUNTIME_RETENTION - ); + assertFieldDoesNotHaveAnnotation(AnnotatedMethods.class, CLASS_RETENTION, METHOD_RUNTIME_RETENTION); + assertFieldDoesNotHaveAnnotation(AnnotatedMethods.class, NO_RETENTION, METHOD_RUNTIME_RETENTION); } @Test @@ -175,76 +117,34 @@ public void findClassAnnotationInMethod() { assertFieldHasAnnotation(AnnotatedMethods.class, CLASS_RETENTION, METHOD_CLASS_RETENTION); assertFieldHasAnnotation(AnnotatedMethods.class, BOTH_RETENTIONS, METHOD_CLASS_RETENTION); - assertFieldDoesNotHaveAnnotation( - AnnotatedMethods.class, - RUNTIME_RETENTION, - METHOD_CLASS_RETENTION - ); - assertFieldDoesNotHaveAnnotation( - AnnotatedMethods.class, - NO_RETENTION, - METHOD_CLASS_RETENTION - ); + assertFieldDoesNotHaveAnnotation(AnnotatedMethods.class, RUNTIME_RETENTION, METHOD_CLASS_RETENTION); + assertFieldDoesNotHaveAnnotation(AnnotatedMethods.class, NO_RETENTION, METHOD_CLASS_RETENTION); } @Test public void findPartialAnnotationName() { - build( - AnnotatedWithRuntime.class, - AnnotatedFields.class, - AnnotatedTypes.class, - AnnotatedMethods.class - ); + build(AnnotatedWithRuntime.class, AnnotatedFields.class, AnnotatedTypes.class, AnnotatedMethods.class); - assertTypeHasAnnotation( - AnnotatedWithRuntime.class, - TYPE_RUNTIME_RETENTION_PARTIAL_CLASSNAME - ); - assertFieldHasAnnotation( - AnnotatedFields.class, - RUNTIME_RETENTION, - FIELD_RUNTIME_RETENTION_PARTIAL_CLASSNAME - ); - assertFieldHasAnnotation( - AnnotatedTypes.class, - RUNTIME_RETENTION, - TYPEUSE_RUNTIME_RETENTION_PARTIAL_CLASSNAME - ); - assertFieldHasAnnotation( - AnnotatedMethods.class, - RUNTIME_RETENTION, - METHOD_RUNTIME_RETENTION_PARTIAL_CLASSNAME - ); + assertTypeHasAnnotation(AnnotatedWithRuntime.class, TYPE_RUNTIME_RETENTION_PARTIAL_CLASSNAME); + assertFieldHasAnnotation(AnnotatedFields.class, RUNTIME_RETENTION, FIELD_RUNTIME_RETENTION_PARTIAL_CLASSNAME); + assertFieldHasAnnotation(AnnotatedTypes.class, RUNTIME_RETENTION, TYPEUSE_RUNTIME_RETENTION_PARTIAL_CLASSNAME); + assertFieldHasAnnotation(AnnotatedMethods.class, RUNTIME_RETENTION, METHOD_RUNTIME_RETENTION_PARTIAL_CLASSNAME); } @Test public void findFullyQualifiedAnnotationName() { - build( - AnnotatedWithRuntime.class, - AnnotatedFields.class, - AnnotatedTypes.class, - AnnotatedMethods.class - ); + build(AnnotatedWithRuntime.class, AnnotatedFields.class, AnnotatedTypes.class, AnnotatedMethods.class); - assertTypeHasAnnotation( - AnnotatedWithRuntime.class, - TYPE_RUNTIME_RETENTION_CANONICAL_CLASSNAME - ); - assertFieldHasAnnotation( - AnnotatedFields.class, - RUNTIME_RETENTION, - FIELD_RUNTIME_RETENTION_CANONICAL_CLASSNAME - ); + assertTypeHasAnnotation(AnnotatedWithRuntime.class, TYPE_RUNTIME_RETENTION_CANONICAL_CLASSNAME); + assertFieldHasAnnotation(AnnotatedFields.class, RUNTIME_RETENTION, FIELD_RUNTIME_RETENTION_CANONICAL_CLASSNAME); assertFieldHasAnnotation( AnnotatedTypes.class, RUNTIME_RETENTION, - TYPEUSE_RUNTIME_RETENTION_CANONICAL_CLASSNAME - ); + TYPEUSE_RUNTIME_RETENTION_CANONICAL_CLASSNAME); assertFieldHasAnnotation( AnnotatedMethods.class, RUNTIME_RETENTION, - METHOD_RUNTIME_RETENTION_CANONICAL_CLASSNAME - ); + METHOD_RUNTIME_RETENTION_CANONICAL_CLASSNAME); } @Test @@ -262,11 +162,7 @@ public void fieldAnnotationInheritance() { assertFieldHasAnnotation(SubclassWithAnnotations.class, "inherits", FIELD_INHERITS); assertFieldHasAnnotation(SuperclassWithAnnotations.class, "inherits", FIELD_INHERITS); - assertFieldDoesNotHaveAnnotation( - SubclassWithAnnotations.class, - "doesntInherit", - FIELD_DOESNT_INHERIT - ); + assertFieldDoesNotHaveAnnotation(SubclassWithAnnotations.class, "doesntInherit", FIELD_DOESNT_INHERIT); } @Test @@ -275,11 +171,7 @@ public void typeUseAnnotationInheritance() { assertFieldHasAnnotation(SubclassWithAnnotations.class, "inherits", TYPEUSE_INHERITS); assertFieldHasAnnotation(SuperclassWithAnnotations.class, "inherits", TYPEUSE_INHERITS); - assertFieldDoesNotHaveAnnotation( - SubclassWithAnnotations.class, - "doesntInherit", - TYPEUSE_DOESNT_INHERIT - ); + assertFieldDoesNotHaveAnnotation(SubclassWithAnnotations.class, "doesntInherit", TYPEUSE_DOESNT_INHERIT); } @Test @@ -294,14 +186,8 @@ public void typeAnnotationInOuterClass() { public void typeAnnotationNestedInOuterClass() { build(AnnotatedOuter.AnnotatedMiddle.AnnotatedInner.class); - assertTypeHasAnnotation( - AnnotatedOuter.AnnotatedMiddle.AnnotatedInner.class, - TYPE_CLASS_RETENTION - ); - assertTypeDoesNotHaveAnnotation( - AnnotatedOuter.AnnotatedMiddle.AnnotatedInner.class, - INAPPLICABLE - ); + assertTypeHasAnnotation(AnnotatedOuter.AnnotatedMiddle.AnnotatedInner.class, TYPE_CLASS_RETENTION); + assertTypeDoesNotHaveAnnotation(AnnotatedOuter.AnnotatedMiddle.AnnotatedInner.class, INAPPLICABLE); } @Test @@ -314,18 +200,11 @@ public void typeAnnotationInPackage() { @Test public void searchIgnoredField() { - cacheBuilder = - new AnnotationCacheBuilder( - TestSupportedAnnotations.values(), - Util.setOf(FieldAnnotationRuntimeRetention.class.getCanonicalName()) - ); + cacheBuilder = new AnnotationCacheBuilder(TestSupportedAnnotations.values(), + Util.setOf(FieldAnnotationRuntimeRetention.class.getCanonicalName())); build(AnnotatedFields.class); - assertFieldDoesNotHaveAnnotation( - AnnotatedFields.class, - "runtimeRetention", - FIELD_RUNTIME_RETENTION - ); + assertFieldDoesNotHaveAnnotation(AnnotatedFields.class, "runtimeRetention", FIELD_RUNTIME_RETENTION); } @Test @@ -340,11 +219,7 @@ public void annotationsAreValidated() { build(InapplicableAnnotations.class); assertTypeDoesNotHaveAnnotation(InapplicableAnnotations.class, INAPPLICABLE); - assertFieldDoesNotHaveAnnotation( - InapplicableAnnotations.class, - "inapplicable", - INAPPLICABLE - ); + assertFieldDoesNotHaveAnnotation(InapplicableAnnotations.class, "inapplicable", INAPPLICABLE); } @Test @@ -359,10 +234,7 @@ public void annotationsArePostProcessed() { public void annotationsEnumParametersAreFoundOnClass() { AnnotationWithClassValuesAnnotation annotation = new AnnotationWithClassValuesAnnotation(); Annotation[] supportedAnnotations = { annotation }; - AnnotationCacheBuilder acb = new AnnotationCacheBuilder( - supportedAnnotations, - NO_INGORED_ANNOTATIONS - ); + AnnotationCacheBuilder acb = new AnnotationCacheBuilder(supportedAnnotations, NO_INGORED_ANNOTATIONS); acb.build(AnnotationWithValuesContainer.class, cache); assertTypeHasAnnotation(AnnotationWithValuesContainer.class, annotation); @@ -375,17 +247,12 @@ public void annotationsEnumParametersAreFoundOnClass() { public void annotationsArrayParametersAreFoundOnClass() { AnnotationWithClassValuesAnnotation annotation = new AnnotationWithClassValuesAnnotation(); Annotation[] supportedAnnotations = { annotation }; - AnnotationCacheBuilder acb = new AnnotationCacheBuilder( - supportedAnnotations, - NO_INGORED_ANNOTATIONS - ); + AnnotationCacheBuilder acb = new AnnotationCacheBuilder(supportedAnnotations, NO_INGORED_ANNOTATIONS); acb.build(AnnotationWithValuesContainer.class, cache); assertTypeHasAnnotation(AnnotationWithValuesContainer.class, annotation); - Set annotations = new HashSet<>( - annotation.properties.getArrayValues("annotations") - ); + Set annotations = new HashSet<>(annotation.properties.getArrayValues("annotations")); assertTrue(annotations.contains("javax.annotation.Nonnull")); assertTrue(annotations.contains("nl.jqno.equalsverifier.testhelpers.annotations.NotNull")); } @@ -408,9 +275,9 @@ public void loadedBySystemClassLoaderDoesNotThrowNullPointerException() { @Test public void dynamicClassDoesntGetProcessed_butDoesntThrowEither() { Class type = Instantiator - .of(AnnotatedWithRuntime.class, new ObjenesisStd()) - .instantiateAnonymousSubclass() - .getClass(); + .of(AnnotatedWithRuntime.class, new ObjenesisStd()) + .instantiateAnonymousSubclass() + .getClass(); build(type); assertTypeDoesNotHaveAnnotation(AnnotatedWithRuntime.class, TYPE_RUNTIME_RETENTION); @@ -419,11 +286,11 @@ public void dynamicClassDoesntGetProcessed_butDoesntThrowEither() { @Test public void generatedClassWithGeneratedFieldDoesNotThrow() { class Super {} - Class sub = Instantiator.giveDynamicSubclass( - Super.class, - "dynamicField", - b -> b.defineField("dynamicField", int.class, Visibility.PRIVATE) - ); + Class sub = Instantiator + .giveDynamicSubclass( + Super.class, + "dynamicField", + b -> b.defineField("dynamicField", int.class, Visibility.PRIVATE)); build(sub); } @@ -445,11 +312,7 @@ private void assertFieldHasAnnotation(Class type, String fieldName, Annotatio assertTrue(cache.hasFieldAnnotation(type, fieldName, annotation)); } - private void assertFieldDoesNotHaveAnnotation( - Class type, - String fieldName, - Annotation annotation - ) { + private void assertFieldDoesNotHaveAnnotation(Class type, String fieldName, Annotation annotation) { assertFalse(cache.hasFieldAnnotation(type, fieldName, annotation)); } @@ -471,18 +334,14 @@ public boolean inherits() { @Override public boolean validate( - AnnotationProperties props, - AnnotationCache annotationCache, - Set ignoredAnnotations - ) { + AnnotationProperties props, + AnnotationCache annotationCache, + Set ignoredAnnotations) { this.properties = props; return true; } } - @AnnotationWithValues( - annotations = { Nonnull.class, NotNull.class }, - elementType = ElementType.FIELD - ) + @AnnotationWithValues(annotations = { Nonnull.class, NotNull.class }, elementType = ElementType.FIELD) private static final class AnnotationWithValuesContainer {} } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/annotations/SupportedAnnotationsTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/annotations/SupportedAnnotationsTest.java index ddcc05671..277b10732 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/annotations/SupportedAnnotationsTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/reflection/annotations/SupportedAnnotationsTest.java @@ -6,6 +6,7 @@ import java.util.HashSet; import java.util.Set; + import org.junit.jupiter.api.Test; public class SupportedAnnotationsTest { @@ -15,38 +16,26 @@ public class SupportedAnnotationsTest { @Test public void jsr305DefaultReturnsTrue_whenAnnotationHasNonnullAnnotation() { - AnnotationProperties props = new AnnotationProperties( - "nl.jqno.equalsverifier.testhelpers.annotations.DefaultNonnullJavax" - ); - boolean actual = SupportedAnnotations.JSR305_DEFAULT_ANNOTATION_NONNULL.validate( - props, - ANNOTATION_CACHE, - NO_IGNORED_ANNOTATIONS - ); + AnnotationProperties props = + new AnnotationProperties("nl.jqno.equalsverifier.testhelpers.annotations.DefaultNonnullJavax"); + boolean actual = SupportedAnnotations.JSR305_DEFAULT_ANNOTATION_NONNULL + .validate(props, ANNOTATION_CACHE, NO_IGNORED_ANNOTATIONS); assertTrue(actual); } @Test public void jsr305DefaultReturnsFalse_whenAnnotationDoesntHaveNonnullAnnotation() { AnnotationProperties props = new AnnotationProperties("javax.annotation.Nonnull"); - boolean actual = SupportedAnnotations.JSR305_DEFAULT_ANNOTATION_NONNULL.validate( - props, - ANNOTATION_CACHE, - NO_IGNORED_ANNOTATIONS - ); + boolean actual = SupportedAnnotations.JSR305_DEFAULT_ANNOTATION_NONNULL + .validate(props, ANNOTATION_CACHE, NO_IGNORED_ANNOTATIONS); assertFalse(actual); } @Test public void jsr305DefaultReturnsFalse_whenTypeDoesNotExist() { - AnnotationProperties props = new AnnotationProperties( - "nl.jqno.equalsverifier.TypeDoesNotExist" - ); - boolean actual = SupportedAnnotations.JSR305_DEFAULT_ANNOTATION_NONNULL.validate( - props, - ANNOTATION_CACHE, - NO_IGNORED_ANNOTATIONS - ); + AnnotationProperties props = new AnnotationProperties("nl.jqno.equalsverifier.TypeDoesNotExist"); + boolean actual = SupportedAnnotations.JSR305_DEFAULT_ANNOTATION_NONNULL + .validate(props, ANNOTATION_CACHE, NO_IGNORED_ANNOTATIONS); assertFalse(actual); } @@ -59,8 +48,6 @@ public void jpaIdAnnotationIsAlsoAddedAsAClassAnnotation() { @Test public void hibernateNaturalIdAnnotationIsAlsoAddedAsAClassAnnotation() { SupportedAnnotations.NATURALID.postProcess(setOf(String.class), ANNOTATION_CACHE); - assertTrue( - ANNOTATION_CACHE.hasClassAnnotation(String.class, SupportedAnnotations.NATURALID) - ); + assertTrue(ANNOTATION_CACHE.hasClassAnnotation(String.class, SupportedAnnotations.NATURALID)); } } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/util/AssertTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/util/AssertTest.java index 206f677a8..65a055ccd 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/util/AssertTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/util/AssertTest.java @@ -25,9 +25,9 @@ public void assertEqualsObjectSuccess() { @Test public void assertEqualsObjectFailure() { ExpectedException - .when(() -> Assert.assertEquals(FAIL, "one", "two")) - .assertThrows(AssertionException.class) - .assertDescriptionContains("fail"); + .when(() -> Assert.assertEquals(FAIL, "one", "two")) + .assertThrows(AssertionException.class) + .assertDescriptionContains("fail"); } @Test @@ -38,9 +38,9 @@ public void assertFalseSuccess() { @Test public void assertFalseFailure() { ExpectedException - .when(() -> Assert.assertFalse(FAIL, true)) - .assertThrows(AssertionException.class) - .assertDescriptionContains("fail"); + .when(() -> Assert.assertFalse(FAIL, true)) + .assertThrows(AssertionException.class) + .assertDescriptionContains("fail"); } @Test @@ -51,16 +51,16 @@ public void assertTrueSuccess() { @Test public void assertTrueFailure() { ExpectedException - .when(() -> Assert.assertTrue(FAIL, false)) - .assertThrows(AssertionException.class) - .assertDescriptionContains("fail"); + .when(() -> Assert.assertTrue(FAIL, false)) + .assertThrows(AssertionException.class) + .assertDescriptionContains("fail"); } @Test public void failFailure() { ExpectedException - .when(() -> Assert.fail(FAIL)) - .assertThrows(AssertionException.class) - .assertDescriptionContains("fail"); + .when(() -> Assert.fail(FAIL)) + .assertThrows(AssertionException.class) + .assertDescriptionContains("fail"); } } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/util/ConfigurationHelper.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/util/ConfigurationHelper.java index 5480ed441..c4848cdc4 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/util/ConfigurationHelper.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/util/ConfigurationHelper.java @@ -1,80 +1,72 @@ package nl.jqno.equalsverifier.internal.util; import java.util.*; + import nl.jqno.equalsverifier.Warning; public final class ConfigurationHelper { private ConfigurationHelper() {} - public static final Configuration emptyConfiguration( - Class type, - Warning... warnings - ) { - return Configuration.build( - type, - Collections.emptySet(), - Collections.emptySet(), - Collections.emptySet(), - Collections.emptySet(), - null, - false, - null, - false, - warnings.length == 0 - ? EnumSet.noneOf(Warning.class) - : EnumSet.copyOf(Arrays.asList(warnings)), - null, - Collections.emptySet(), - Collections.emptySet(), - Collections.emptyList(), - Collections.emptyList() - ); + public static final Configuration emptyConfiguration(Class type, Warning... warnings) { + return Configuration + .build( + type, + Collections.emptySet(), + Collections.emptySet(), + Collections.emptySet(), + Collections.emptySet(), + null, + false, + null, + false, + warnings.length == 0 ? EnumSet.noneOf(Warning.class) : EnumSet.copyOf(Arrays.asList(warnings)), + null, + Collections.emptySet(), + Collections.emptySet(), + Collections.emptyList(), + Collections.emptyList()); } - public static final Configuration emptyConfigurationWithNonnullFields( - Class type, - String... fieldNames - ) { - return Configuration.build( - type, - Collections.emptySet(), - Collections.emptySet(), - new HashSet<>(Arrays.asList(fieldNames)), - Collections.emptySet(), - null, - false, - null, - false, - EnumSet.noneOf(Warning.class), - null, - Collections.emptySet(), - Collections.emptySet(), - Collections.emptyList(), - Collections.emptyList() - ); + public static final Configuration emptyConfigurationWithNonnullFields(Class type, String... fieldNames) { + return Configuration + .build( + type, + Collections.emptySet(), + Collections.emptySet(), + new HashSet<>(Arrays.asList(fieldNames)), + Collections.emptySet(), + null, + false, + null, + false, + EnumSet.noneOf(Warning.class), + null, + Collections.emptySet(), + Collections.emptySet(), + Collections.emptyList(), + Collections.emptyList()); } public static final Configuration emptyConfigurationWithPrefabbedFields( - Class type, - String... fieldNames - ) { - return Configuration.build( - type, - Collections.emptySet(), - Collections.emptySet(), - Collections.emptySet(), - new HashSet<>(Arrays.asList(fieldNames)), - null, - false, - null, - false, - EnumSet.noneOf(Warning.class), - null, - Collections.emptySet(), - Collections.emptySet(), - Collections.emptyList(), - Collections.emptyList() - ); + Class type, + String... fieldNames) { + return Configuration + .build( + type, + Collections.emptySet(), + Collections.emptySet(), + Collections.emptySet(), + new HashSet<>(Arrays.asList(fieldNames)), + null, + false, + null, + false, + EnumSet.noneOf(Warning.class), + null, + Collections.emptySet(), + Collections.emptySet(), + Collections.emptyList(), + Collections.emptyList()); } } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/util/FieldNameExtractorTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/util/FieldNameExtractorTest.java index b3cd24bf9..52cadd799 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/util/FieldNameExtractorTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/util/FieldNameExtractorTest.java @@ -6,6 +6,7 @@ import java.util.List; import java.util.Set; + import org.junit.jupiter.api.Test; public class FieldNameExtractorTest { @@ -24,9 +25,7 @@ public void coverTheConstructor() { @Test public void should_extractFields_succesfully() { - Set fields = FieldNameExtractor.extractFieldNames( - FieldNameExtractorTestHelper.class - ); + Set fields = FieldNameExtractor.extractFieldNames(FieldNameExtractorTestHelper.class); assertTrue(fields.contains(FIELD_STRING), FIELD_NOT_FOUND + FIELD_STRING); assertTrue(fields.contains(FIELD_OBJECT), FIELD_NOT_FOUND + FIELD_OBJECT); @@ -38,21 +37,14 @@ public void should_extractFields_succesfully() { @Test public void should_disallow_adding_extra_fields() { - Set fields = FieldNameExtractor.extractFieldNames( - FieldNameExtractorTestHelper.class - ); - - assertThrows( - UnsupportedOperationException.class, - () -> fields.add("illegally added field") - ); + Set fields = FieldNameExtractor.extractFieldNames(FieldNameExtractorTestHelper.class); + + assertThrows(UnsupportedOperationException.class, () -> fields.add("illegally added field")); } @Test public void should_disallow_removing_fields() { - Set fields = FieldNameExtractor.extractFieldNames( - FieldNameExtractorTestHelper.class - ); + Set fields = FieldNameExtractor.extractFieldNames(FieldNameExtractorTestHelper.class); assertThrows(UnsupportedOperationException.class, () -> fields.remove(FIELD_STRING)); } @@ -64,11 +56,7 @@ class FieldNameExtractorTestHelper { final List fieldList; private final Object fieldObject; - public FieldNameExtractorTestHelper( - String fieldString, - List fieldList, - Object fieldObject - ) { + public FieldNameExtractorTestHelper(String fieldString, List fieldList, Object fieldObject) { this.fieldString = fieldString; this.fieldList = fieldList; this.fieldObject = fieldObject; diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/util/FormatterTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/util/FormatterTest.java index ac26e1721..c05c493cb 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/util/FormatterTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/util/FormatterTest.java @@ -29,16 +29,9 @@ public void oneSimpleParameter() { @Test public void multipleSimpleParameters() { - Formatter f = Formatter.of( - "Multiple simple parameters: %% and %% and also %%", - new Simple(0), - new Simple(1), - new Simple(2) - ); - assertEquals( - "Multiple simple parameters: Simple: 0 and Simple: 1 and also Simple: 2", - f.format() - ); + Formatter f = Formatter + .of("Multiple simple parameters: %% and %% and also %%", new Simple(0), new Simple(1), new Simple(2)); + assertEquals("Multiple simple parameters: Simple: 0 and Simple: 1 and also Simple: 2", f.format()); } @Test @@ -46,29 +39,21 @@ public void oneThrowingParameter() { Formatter f = Formatter.of("One throwing parameter: %%", new Throwing(1337, "string")); assertEquals( "One throwing parameter: [Throwing i=1337 s=string]-throws IllegalStateException(msg)", - f.format() - ); + f.format()); } @Test public void oneThrowingParameterWithNullSubparameter() { Formatter f = Formatter.of("One throwing parameter: %%", new Throwing(1337, null)); - assertEquals( - "One throwing parameter: [Throwing i=1337 s=null]-throws IllegalStateException(msg)", - f.format() - ); + assertEquals("One throwing parameter: [Throwing i=1337 s=null]-throws IllegalStateException(msg)", f.format()); } @Test public void oneParameterWithNoFieldsAndThrowsWithNullMessage() { - Formatter f = Formatter.of( - "No fields, null message: %%", - new NoFieldsAndThrowsNullMessage() - ); + Formatter f = Formatter.of("No fields, null message: %%", new NoFieldsAndThrowsNullMessage()); assertEquals( "No fields, null message: [NoFieldsAndThrowsNullMessage (no fields)]-throws NullPointerException(null)", - f.format() - ); + f.format()); } @Test @@ -94,10 +79,7 @@ public void oneDelegatedAbstractParameter() { @Test public void oneDelegatedConcreteSubclassParameter() { - Instantiator i = Instantiator.of( - AbstractDelegationImpl.class, - objenesis - ); + Instantiator i = Instantiator.of(AbstractDelegationImpl.class, objenesis); Formatter f = Formatter.of("Concrete: %%", i.instantiate()); assertThat(f.format(), containsString("Concrete: something concrete")); } @@ -108,7 +90,7 @@ public void oneThrowingContainerParameter() { ThrowingContainer tc = new ThrowingContainer(i.instantiate()); Formatter f = Formatter.of("TC: %%", tc); String expected = - "TC: [ThrowingContainer t=[Throwing i=0 s=null]-throws IllegalStateException(msg)]-throws IllegalStateException(msg)"; + "TC: [ThrowingContainer t=[Throwing i=0 s=null]-throws IllegalStateException(msg)]-throws IllegalStateException(msg)"; assertThat(f.format(), containsString(expected)); } @@ -118,10 +100,7 @@ public void oneAbstractContainerParameter() { AbstractContainer ac = new AbstractContainer(i.instantiate()); Formatter f = Formatter.of("AC: %%", ac); - assertThat( - f.format(), - containsString("AC: [AbstractContainer ad=[AbstractDelegation y=0]]") - ); + assertThat(f.format(), containsString("AC: [AbstractContainer ad=[AbstractDelegation y=0]]")); } @Test @@ -131,8 +110,8 @@ public void parameterWithMixOfVariousFields() { Formatter f = Formatter.of("%%", mix); String expected = - "[Mix i=42 s=null t=not null throwing=[Throwing i=42 s=empty]-throws IllegalStateException(msg)]" + - "-throws UnsupportedOperationException(null)"; + "[Mix i=42 s=null t=not null throwing=[Throwing i=42 s=empty]-throws IllegalStateException(msg)]" + + "-throws UnsupportedOperationException(null)"; assertThat(f.format(), containsString(expected)); } @@ -158,9 +137,9 @@ public void notEnoughParameters() { Formatter f = Formatter.of("Not enough: %% and %%"); ExpectedException - .when(() -> f.format()) - .assertThrows(IllegalStateException.class) - .assertMessageContains("Not enough parameters"); + .when(() -> f.format()) + .assertThrows(IllegalStateException.class) + .assertMessageContains("Not enough parameters"); } @Test @@ -168,9 +147,9 @@ public void tooManyParameters() { Formatter f = Formatter.of("Too many!", new Simple(0)); ExpectedException - .when(() -> f.format()) - .assertThrows(IllegalStateException.class) - .assertMessageContains("Too many parameters"); + .when(() -> f.format()) + .assertThrows(IllegalStateException.class) + .assertMessageContains("Too many parameters"); } static class Simple { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/util/RethrowTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/util/RethrowTest.java index b6af751eb..a41ded7a9 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/util/RethrowTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/util/RethrowTest.java @@ -4,6 +4,7 @@ import static nl.jqno.equalsverifier.internal.util.Rethrow.rethrow; import java.io.IOException; + import nl.jqno.equalsverifier.internal.exceptions.EqualsVerifierInternalBugException; import nl.jqno.equalsverifier.internal.exceptions.ReflectionException; import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; @@ -24,97 +25,97 @@ public void coverTheConstructor() { @Test public void supplierWithIgnoredMessageThrowsRuntimeException() { ExpectedException - .when(() -> rethrow(supply(new RuntimeException(CAUSE_MSG)), e -> PROVIDED_MSG)) - .assertThrows(RuntimeException.class) - .assertMessageContains(CAUSE_MSG); + .when(() -> rethrow(supply(new RuntimeException(CAUSE_MSG)), e -> PROVIDED_MSG)) + .assertThrows(RuntimeException.class) + .assertMessageContains(CAUSE_MSG); } @Test public void supplierWithMessageThrowsReflectiveOperationException() { ExpectedException - .when(() -> rethrow(supply(new IllegalAccessException(CAUSE_MSG)), e -> PROVIDED_MSG)) - .assertThrows(ReflectionException.class) - .assertMessageContains(PROVIDED_MSG); + .when(() -> rethrow(supply(new IllegalAccessException(CAUSE_MSG)), e -> PROVIDED_MSG)) + .assertThrows(ReflectionException.class) + .assertMessageContains(PROVIDED_MSG); } @Test public void supplierWithMessageThrowsException() { ExpectedException - .when(() -> rethrow(supply(new IOException(CAUSE_MSG)), e -> PROVIDED_MSG)) - .assertThrows(EqualsVerifierInternalBugException.class) - .assertMessageContains(PROVIDED_MSG); + .when(() -> rethrow(supply(new IOException(CAUSE_MSG)), e -> PROVIDED_MSG)) + .assertThrows(EqualsVerifierInternalBugException.class) + .assertMessageContains(PROVIDED_MSG); } @Test public void supplierWithNoMessageThrowsRuntimeException() { ExpectedException - .when(() -> rethrow(supply(new RuntimeException(CAUSE_MSG)))) - .assertThrows(RuntimeException.class) - .assertMessageContains(CAUSE_MSG); + .when(() -> rethrow(supply(new RuntimeException(CAUSE_MSG)))) + .assertThrows(RuntimeException.class) + .assertMessageContains(CAUSE_MSG); } @Test public void supplierWithNoMessageThrowsReflectiveOperationException() { ExpectedException - .when(() -> rethrow(supply(new IllegalAccessException(CAUSE_MSG)))) - .assertThrows(ReflectionException.class) - .assertMessageContains(CAUSE_MSG); + .when(() -> rethrow(supply(new IllegalAccessException(CAUSE_MSG)))) + .assertThrows(ReflectionException.class) + .assertMessageContains(CAUSE_MSG); } @Test public void supplierWithNoMessageThrowsException() { ExpectedException - .when(() -> rethrow(supply(new IOException(CAUSE_MSG)))) - .assertThrows(EqualsVerifierInternalBugException.class) - .assertMessageContains(CAUSE_MSG); + .when(() -> rethrow(supply(new IOException(CAUSE_MSG)))) + .assertThrows(EqualsVerifierInternalBugException.class) + .assertMessageContains(CAUSE_MSG); } @Test public void runnableWithIgnoredMessageThrowsRuntimeException() { ExpectedException - .when(() -> rethrow(run(new RuntimeException(CAUSE_MSG)), e -> PROVIDED_MSG)) - .assertThrows(RuntimeException.class) - .assertMessageContains(CAUSE_MSG); + .when(() -> rethrow(run(new RuntimeException(CAUSE_MSG)), e -> PROVIDED_MSG)) + .assertThrows(RuntimeException.class) + .assertMessageContains(CAUSE_MSG); } @Test public void runnableWithMessageThrowsReflectiveOperationException() { ExpectedException - .when(() -> rethrow(run(new IllegalAccessException(CAUSE_MSG)), e -> PROVIDED_MSG)) - .assertThrows(ReflectionException.class) - .assertMessageContains(PROVIDED_MSG); + .when(() -> rethrow(run(new IllegalAccessException(CAUSE_MSG)), e -> PROVIDED_MSG)) + .assertThrows(ReflectionException.class) + .assertMessageContains(PROVIDED_MSG); } @Test public void runnableWithMessageThrowsException() { ExpectedException - .when(() -> rethrow(run(new IOException(CAUSE_MSG)), e -> PROVIDED_MSG)) - .assertThrows(EqualsVerifierInternalBugException.class) - .assertMessageContains(PROVIDED_MSG); + .when(() -> rethrow(run(new IOException(CAUSE_MSG)), e -> PROVIDED_MSG)) + .assertThrows(EqualsVerifierInternalBugException.class) + .assertMessageContains(PROVIDED_MSG); } @Test public void runnableWithNoMessageThrowsRuntimeException() { ExpectedException - .when(() -> rethrow(run(new RuntimeException(CAUSE_MSG)))) - .assertThrows(RuntimeException.class) - .assertMessageContains(CAUSE_MSG); + .when(() -> rethrow(run(new RuntimeException(CAUSE_MSG)))) + .assertThrows(RuntimeException.class) + .assertMessageContains(CAUSE_MSG); } @Test public void runnableWithNoMessageThrowsReflectiveOperationException() { ExpectedException - .when(() -> rethrow(run(new IllegalAccessException(CAUSE_MSG)))) - .assertThrows(ReflectionException.class) - .assertMessageContains(CAUSE_MSG); + .when(() -> rethrow(run(new IllegalAccessException(CAUSE_MSG)))) + .assertThrows(ReflectionException.class) + .assertMessageContains(CAUSE_MSG); } @Test public void runnableWithNoMessageThrowsException() { ExpectedException - .when(() -> rethrow(run(new IOException(CAUSE_MSG)))) - .assertThrows(EqualsVerifierInternalBugException.class) - .assertMessageContains(CAUSE_MSG); + .when(() -> rethrow(run(new IOException(CAUSE_MSG)))) + .assertThrows(EqualsVerifierInternalBugException.class) + .assertMessageContains(CAUSE_MSG); } private ThrowingSupplier supply(Exception e) { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/util/ValidationsTest.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/util/ValidationsTest.java index 3906f1183..00984a308 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/util/ValidationsTest.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/internal/util/ValidationsTest.java @@ -8,6 +8,7 @@ import java.util.Collection; import java.util.HashSet; import java.util.List; + import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException; import org.junit.jupiter.api.Test; @@ -20,110 +21,53 @@ public void coverTheConstructor() { @Test public void validateFieldTypeMatches_shouldFailOnWrongType() { - assertAll( - () -> { - ExpectedException - .when(() -> - Validations.validateFieldTypeMatches( - TestContainer.class, - "listField", - HashSet.class - ) - ) + assertAll(() -> { + ExpectedException + .when(() -> Validations.validateFieldTypeMatches(TestContainer.class, "listField", HashSet.class)) .assertThrows(IllegalStateException.class) .assertMessageContains("should be of type List", "but are HashSet"); - }, - () -> { - ExpectedException - .when(() -> - Validations.validateFieldTypeMatches( - TestContainer.class, - "objectField", - int.class - ) - ) + }, () -> { + ExpectedException + .when(() -> Validations.validateFieldTypeMatches(TestContainer.class, "objectField", int.class)) .assertThrows(IllegalStateException.class) .assertMessageContains("should be of type Object", "but are int"); - }, - () -> { - ExpectedException - .when(() -> - Validations.validateFieldTypeMatches( - TestContainer.class, - "charsField", - Character.class - ) - ) + }, () -> { + ExpectedException + .when( + () -> Validations.validateFieldTypeMatches(TestContainer.class, "charsField", Character.class)) .assertThrows(IllegalStateException.class) .assertMessageContains("should be of type CharSequence", "but are Character"); - } - ); + }); } @Test public void validateFieldTypeMatches_shouldAllowSubTypes() { assertAll( - () -> - assertDoesNotThrow( - () -> - Validations.validateFieldTypeMatches( - TestContainer.class, - "listField", - ArrayList.class - ), - "Should allow ArrayList as a List" - ), - () -> - assertDoesNotThrow( - () -> - Validations.validateFieldTypeMatches( - TestContainer.class, - "objectField", - Integer.class - ), - "Should allow Integer as an Object" - ), - () -> - assertDoesNotThrow( - () -> - Validations.validateFieldTypeMatches( - TestContainer.class, - "charsField", - String.class - ), - "Should allow String as a CharSequence" - ) - ); + () -> assertDoesNotThrow( + () -> Validations.validateFieldTypeMatches(TestContainer.class, "listField", ArrayList.class), + "Should allow ArrayList as a List"), + () -> assertDoesNotThrow( + () -> Validations.validateFieldTypeMatches(TestContainer.class, "objectField", Integer.class), + "Should allow Integer as an Object"), + () -> assertDoesNotThrow( + () -> Validations.validateFieldTypeMatches(TestContainer.class, "charsField", String.class), + "Should allow String as a CharSequence")); } @Test public void validateFieldTypeMatches_shouldFailOnSuperTypes() { - assertAll( - () -> { - ExpectedException - .when(() -> - Validations.validateFieldTypeMatches( - TestContainer.class, - "listField", - Collection.class - ) - ) + assertAll(() -> { + ExpectedException + .when( + () -> Validations.validateFieldTypeMatches(TestContainer.class, "listField", Collection.class)) .assertThrows(IllegalStateException.class) .assertMessageContains("should be of type List", "but are Collection"); - }, - () -> { - ExpectedException - .when(() -> - Validations.validateFieldTypeMatches( - TestContainer.class, - "charsField", - Object.class - ) - ) + }, () -> { + ExpectedException + .when(() -> Validations.validateFieldTypeMatches(TestContainer.class, "charsField", Object.class)) .assertThrows(IllegalStateException.class) .assertMessageContains("should be of type CharSequence", "but are Object"); - } - ); + }); } @SuppressWarnings("unused") diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/AnnotationWithAnnotation.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/AnnotationWithAnnotation.java index 03d951632..bca16f7a3 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/AnnotationWithAnnotation.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/AnnotationWithAnnotation.java @@ -5,5 +5,4 @@ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @TypeAnnotationClassRetention -public @interface AnnotationWithAnnotation { -} +public @interface AnnotationWithAnnotation {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/DefaultNonnullCustom.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/DefaultNonnullCustom.java index 332f9503f..cbee5db36 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/DefaultNonnullCustom.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/DefaultNonnullCustom.java @@ -10,5 +10,4 @@ @NotNull @TypeQualifierDefault(ElementType.FIELD) @Retention(RetentionPolicy.CLASS) -public @interface DefaultNonnullCustom { -} +public @interface DefaultNonnullCustom {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/DefaultNonnullInapplicable.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/DefaultNonnullInapplicable.java index d86434e4d..39cc8d3bc 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/DefaultNonnullInapplicable.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/DefaultNonnullInapplicable.java @@ -11,5 +11,4 @@ @Nonnull @TypeQualifierDefault(ElementType.TYPE) @Retention(RetentionPolicy.CLASS) -public @interface DefaultNonnullInapplicable { -} +public @interface DefaultNonnullInapplicable {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/DefaultNonnullJavax.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/DefaultNonnullJavax.java index c76610a53..5cbd94f6a 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/DefaultNonnullJavax.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/DefaultNonnullJavax.java @@ -5,11 +5,11 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import javax.annotation.meta.TypeQualifierDefault; + import nl.jqno.equalsverifier.testhelpers.annotations.javax.annotation.Nonnull; @Documented @Nonnull @TypeQualifierDefault({ ElementType.FIELD, ElementType.TYPE }) @Retention(RetentionPolicy.CLASS) -public @interface DefaultNonnullJavax { -} +public @interface DefaultNonnullJavax {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/Embeddable.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/Embeddable.java index 0cf0c6be9..ad66bbfa4 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/Embeddable.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/Embeddable.java @@ -7,5 +7,4 @@ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) -public @interface Embeddable { -} +public @interface Embeddable {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/Entity.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/Entity.java index 9bd3b4017..30a9cdc06 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/Entity.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/Entity.java @@ -7,5 +7,4 @@ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) -public @interface Entity { -} +public @interface Entity {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/FieldAnnotationClassRetention.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/FieldAnnotationClassRetention.java index fe1e16c13..5bca61852 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/FieldAnnotationClassRetention.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/FieldAnnotationClassRetention.java @@ -7,5 +7,4 @@ @Target(ElementType.FIELD) @Retention(RetentionPolicy.CLASS) -public @interface FieldAnnotationClassRetention { -} +public @interface FieldAnnotationClassRetention {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/FieldAnnotationDoesntInherit.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/FieldAnnotationDoesntInherit.java index 791e8962a..fc491c8f3 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/FieldAnnotationDoesntInherit.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/FieldAnnotationDoesntInherit.java @@ -7,5 +7,4 @@ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) -public @interface FieldAnnotationDoesntInherit { -} +public @interface FieldAnnotationDoesntInherit {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/FieldAnnotationInherits.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/FieldAnnotationInherits.java index 6c30abd77..a7ebf933d 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/FieldAnnotationInherits.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/FieldAnnotationInherits.java @@ -7,5 +7,4 @@ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) -public @interface FieldAnnotationInherits { -} +public @interface FieldAnnotationInherits {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/FieldAnnotationRuntimeRetention.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/FieldAnnotationRuntimeRetention.java index 7e16d33ec..762bf77b9 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/FieldAnnotationRuntimeRetention.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/FieldAnnotationRuntimeRetention.java @@ -7,5 +7,4 @@ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) -public @interface FieldAnnotationRuntimeRetention { -} +public @interface FieldAnnotationRuntimeRetention {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/Id.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/Id.java index 4aa349288..3800e4c54 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/Id.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/Id.java @@ -7,5 +7,4 @@ @Target({ ElementType.METHOD, ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) -public @interface Id { -} +public @interface Id {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/Immutable.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/Immutable.java index bedb33b89..6381464c5 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/Immutable.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/Immutable.java @@ -6,10 +6,9 @@ import java.lang.annotation.Target; /** - * Because there's no standard Immutable annotation, we define our own so that EqualsVerifier can - * work with any annotation called Immutable. + * Because there's no standard Immutable annotation, we define our own so that EqualsVerifier can work with any + * annotation called Immutable. */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) -public @interface Immutable { -} +public @interface Immutable {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/Inapplicable.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/Inapplicable.java index 9d4e2b46d..894762cf0 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/Inapplicable.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/Inapplicable.java @@ -7,5 +7,4 @@ @Target({ ElementType.FIELD, ElementType.TYPE }) @Retention(RetentionPolicy.CLASS) -public @interface Inapplicable { -} +public @interface Inapplicable {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/MappedSuperclass.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/MappedSuperclass.java index 615c067c3..e6ccc2ac0 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/MappedSuperclass.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/MappedSuperclass.java @@ -7,5 +7,4 @@ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) -public @interface MappedSuperclass { -} +public @interface MappedSuperclass {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/MethodAnnotationClassRetention.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/MethodAnnotationClassRetention.java index 344caca2e..acda945da 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/MethodAnnotationClassRetention.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/MethodAnnotationClassRetention.java @@ -7,5 +7,4 @@ @Target(ElementType.METHOD) @Retention(RetentionPolicy.CLASS) -public @interface MethodAnnotationClassRetention { -} +public @interface MethodAnnotationClassRetention {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/MethodAnnotationRuntimeRetention.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/MethodAnnotationRuntimeRetention.java index 14af95b3b..1e8f0f01d 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/MethodAnnotationRuntimeRetention.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/MethodAnnotationRuntimeRetention.java @@ -7,5 +7,4 @@ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) -public @interface MethodAnnotationRuntimeRetention { -} +public @interface MethodAnnotationRuntimeRetention {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/NaturalId.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/NaturalId.java index b819682c9..bc7b7a97f 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/NaturalId.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/NaturalId.java @@ -7,5 +7,4 @@ @Target({ ElementType.METHOD, ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) -public @interface NaturalId { -} +public @interface NaturalId {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/NonNull.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/NonNull.java index f958f0236..cfcaeaa7b 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/NonNull.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/NonNull.java @@ -6,10 +6,9 @@ import java.lang.annotation.Target; /** - * Because there's no standard Nonnull/NonNull/NotNull annotation, we define our own so that - * EqualsVerifier can work with any non-null annotation. + * Because there's no standard Nonnull/NonNull/NotNull annotation, we define our own so that EqualsVerifier can work + * with any non-null annotation. */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.CLASS) -public @interface NonNull { -} +public @interface NonNull {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/NotNull.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/NotNull.java index 184b6fc92..1c925d032 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/NotNull.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/NotNull.java @@ -6,10 +6,9 @@ import java.lang.annotation.Target; /** - * Because there's no standard Nonnull/NonNull/NotNull annotation, we define our own so that - * EqualsVerifier can work with any non-null annotation. + * Because there's no standard Nonnull/NonNull/NotNull annotation, we define our own so that EqualsVerifier can work + * with any non-null annotation. */ @Target({ ElementType.FIELD, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.CLASS) -public @interface NotNull { -} +public @interface NotNull {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/PackageAnnotation.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/PackageAnnotation.java index 851051ed1..d66ef1736 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/PackageAnnotation.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/PackageAnnotation.java @@ -7,5 +7,4 @@ @Target(ElementType.PACKAGE) @Retention(RetentionPolicy.CLASS) -public @interface PackageAnnotation { -} +public @interface PackageAnnotation {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/PostProcess.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/PostProcess.java index c3b78b29d..da2b63e3f 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/PostProcess.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/PostProcess.java @@ -7,5 +7,4 @@ @Target(ElementType.FIELD) @Retention(RetentionPolicy.CLASS) -public @interface PostProcess { -} +public @interface PostProcess {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TestSupportedAnnotations.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TestSupportedAnnotations.java index 7b32bedaa..b3f0cdfe7 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TestSupportedAnnotations.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TestSupportedAnnotations.java @@ -3,64 +3,30 @@ import java.util.Arrays; import java.util.HashSet; import java.util.Set; + import nl.jqno.equalsverifier.internal.reflection.annotations.Annotation; import nl.jqno.equalsverifier.internal.reflection.annotations.AnnotationCache; import nl.jqno.equalsverifier.internal.reflection.annotations.AnnotationProperties; public enum TestSupportedAnnotations implements Annotation { - TYPE_RUNTIME_RETENTION( - false, - "nl.jqno.equalsverifier.testhelpers.annotations.TypeAnnotationRuntimeRetention" - ), - TYPE_CLASS_RETENTION( - false, - "nl.jqno.equalsverifier.testhelpers.annotations.TypeAnnotationClassRetention" - ), - FIELD_RUNTIME_RETENTION( - false, - "nl.jqno.equalsverifier.testhelpers.annotations.FieldAnnotationRuntimeRetention" - ), - FIELD_CLASS_RETENTION( - false, - "nl.jqno.equalsverifier.testhelpers.annotations.FieldAnnotationClassRetention" - ), - TYPEUSE_RUNTIME_RETENTION( - false, - "nl.jqno.equalsverifier.testhelpers.annotations.TypeUseAnnotationRuntimeRetention" - ), - TYPEUSE_CLASS_RETENTION( - false, - "nl.jqno.equalsverifier.testhelpers.annotations.TypeUseAnnotationClassRetention" - ), - METHOD_RUNTIME_RETENTION( - false, - "nl.jqno.equalsverifier.testhelpers.annotations.MethodAnnotationRuntimeRetention" - ), - METHOD_CLASS_RETENTION( - false, - "nl.jqno.equalsverifier.testhelpers.annotations.MethodAnnotationClassRetention" - ), + TYPE_RUNTIME_RETENTION(false, "nl.jqno.equalsverifier.testhelpers.annotations.TypeAnnotationRuntimeRetention"), + TYPE_CLASS_RETENTION(false, "nl.jqno.equalsverifier.testhelpers.annotations.TypeAnnotationClassRetention"), + FIELD_RUNTIME_RETENTION(false, "nl.jqno.equalsverifier.testhelpers.annotations.FieldAnnotationRuntimeRetention"), + FIELD_CLASS_RETENTION(false, "nl.jqno.equalsverifier.testhelpers.annotations.FieldAnnotationClassRetention"), + TYPEUSE_RUNTIME_RETENTION(false, + "nl.jqno.equalsverifier.testhelpers.annotations.TypeUseAnnotationRuntimeRetention"), + TYPEUSE_CLASS_RETENTION(false, "nl.jqno.equalsverifier.testhelpers.annotations.TypeUseAnnotationClassRetention"), + METHOD_RUNTIME_RETENTION(false, "nl.jqno.equalsverifier.testhelpers.annotations.MethodAnnotationRuntimeRetention"), + METHOD_CLASS_RETENTION(false, "nl.jqno.equalsverifier.testhelpers.annotations.MethodAnnotationClassRetention"), TYPE_RUNTIME_RETENTION_PARTIAL_CLASSNAME(false, "TypeAnnotationRuntimeRetention"), - TYPE_RUNTIME_RETENTION_CANONICAL_CLASSNAME( - false, - TypeAnnotationRuntimeRetention.class.getCanonicalName() - ), + TYPE_RUNTIME_RETENTION_CANONICAL_CLASSNAME(false, TypeAnnotationRuntimeRetention.class.getCanonicalName()), FIELD_RUNTIME_RETENTION_PARTIAL_CLASSNAME(false, "FieldAnnotationRuntimeRetention"), - FIELD_RUNTIME_RETENTION_CANONICAL_CLASSNAME( - false, - FieldAnnotationRuntimeRetention.class.getCanonicalName() - ), + FIELD_RUNTIME_RETENTION_CANONICAL_CLASSNAME(false, FieldAnnotationRuntimeRetention.class.getCanonicalName()), TYPEUSE_RUNTIME_RETENTION_PARTIAL_CLASSNAME(false, "TypeUseAnnotationRuntimeRetention"), - TYPEUSE_RUNTIME_RETENTION_CANONICAL_CLASSNAME( - false, - TypeUseAnnotationRuntimeRetention.class.getCanonicalName() - ), + TYPEUSE_RUNTIME_RETENTION_CANONICAL_CLASSNAME(false, TypeUseAnnotationRuntimeRetention.class.getCanonicalName()), METHOD_RUNTIME_RETENTION_PARTIAL_CLASSNAME(false, "MethodAnnotationRuntimeRetention"), - METHOD_RUNTIME_RETENTION_CANONICAL_CLASSNAME( - false, - MethodAnnotationRuntimeRetention.class.getCanonicalName() - ), + METHOD_RUNTIME_RETENTION_CANONICAL_CLASSNAME(false, MethodAnnotationRuntimeRetention.class.getCanonicalName()), TYPE_INHERITS(true, "TypeAnnotationInherits"), TYPE_DOESNT_INHERIT(false, "TypeAnnotationDoesntInherit"), @@ -73,10 +39,9 @@ public enum TestSupportedAnnotations implements Annotation { INAPPLICABLE(false, "Inapplicable") { @Override public boolean validate( - AnnotationProperties properties, - AnnotationCache annotationCache, - Set ignoredAnnotations - ) { + AnnotationProperties properties, + AnnotationCache annotationCache, + Set ignoredAnnotations) { return false; } }, diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/Transient.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/Transient.java index 9d836d0d9..af8cf1a72 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/Transient.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/Transient.java @@ -7,5 +7,4 @@ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) -public @interface Transient { -} +public @interface Transient {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeAnnotationClassRetention.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeAnnotationClassRetention.java index 5f14bec5c..8c4436749 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeAnnotationClassRetention.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeAnnotationClassRetention.java @@ -7,5 +7,4 @@ @Target(ElementType.TYPE) @Retention(RetentionPolicy.CLASS) -public @interface TypeAnnotationClassRetention { -} +public @interface TypeAnnotationClassRetention {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeAnnotationDoesntInherit.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeAnnotationDoesntInherit.java index b9e18122e..2e080459b 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeAnnotationDoesntInherit.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeAnnotationDoesntInherit.java @@ -7,5 +7,4 @@ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) -public @interface TypeAnnotationDoesntInherit { -} +public @interface TypeAnnotationDoesntInherit {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeAnnotationInherits.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeAnnotationInherits.java index d8122d2bb..777d06bf3 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeAnnotationInherits.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeAnnotationInherits.java @@ -7,5 +7,4 @@ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) -public @interface TypeAnnotationInherits { -} +public @interface TypeAnnotationInherits {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeAnnotationRuntimeRetention.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeAnnotationRuntimeRetention.java index 02535bb4e..a6d526d14 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeAnnotationRuntimeRetention.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeAnnotationRuntimeRetention.java @@ -7,5 +7,4 @@ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) -public @interface TypeAnnotationRuntimeRetention { -} +public @interface TypeAnnotationRuntimeRetention {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeUseAnnotationClassRetention.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeUseAnnotationClassRetention.java index 785167f7d..3a90c1b9e 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeUseAnnotationClassRetention.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeUseAnnotationClassRetention.java @@ -7,5 +7,4 @@ @Target(ElementType.TYPE_USE) @Retention(RetentionPolicy.CLASS) -public @interface TypeUseAnnotationClassRetention { -} +public @interface TypeUseAnnotationClassRetention {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeUseAnnotationDoesntInherit.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeUseAnnotationDoesntInherit.java index 66b0ebc71..005d9a3e4 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeUseAnnotationDoesntInherit.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeUseAnnotationDoesntInherit.java @@ -7,5 +7,4 @@ @Target(ElementType.TYPE_USE) @Retention(RetentionPolicy.RUNTIME) -public @interface TypeUseAnnotationDoesntInherit { -} +public @interface TypeUseAnnotationDoesntInherit {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeUseAnnotationInherits.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeUseAnnotationInherits.java index 354b52e7d..b3533e7b9 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeUseAnnotationInherits.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeUseAnnotationInherits.java @@ -7,5 +7,4 @@ @Target(ElementType.TYPE_USE) @Retention(RetentionPolicy.RUNTIME) -public @interface TypeUseAnnotationInherits { -} +public @interface TypeUseAnnotationInherits {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeUseAnnotationRuntimeRetention.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeUseAnnotationRuntimeRetention.java index 1bed86ad0..1c1297c6d 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeUseAnnotationRuntimeRetention.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/TypeUseAnnotationRuntimeRetention.java @@ -7,5 +7,4 @@ @Target(ElementType.TYPE_USE) @Retention(RetentionPolicy.RUNTIME) -public @interface TypeUseAnnotationRuntimeRetention { -} +public @interface TypeUseAnnotationRuntimeRetention {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/edu/umd/cs/findbugs/annotations/DefaultAnnotation.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/edu/umd/cs/findbugs/annotations/DefaultAnnotation.java index de6920b23..7d9a7a3f7 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/edu/umd/cs/findbugs/annotations/DefaultAnnotation.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/edu/umd/cs/findbugs/annotations/DefaultAnnotation.java @@ -3,9 +3,8 @@ import java.lang.annotation.*; /** - * This annotation serves as a paceholder for the real {@link - * edu.umd.cs.findbugs.annotations.DefaultAnnotation}, which is deprecated. We use this annotation - * to avoid warnings in places where we can't suppress the warning. + * This annotation serves as a paceholder for the real {@link edu.umd.cs.findbugs.annotations.DefaultAnnotation}, which + * is deprecated. We use this annotation to avoid warnings in places where we can't suppress the warning. */ @Target(ElementType.PACKAGE) @Retention(RetentionPolicy.CLASS) diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/annotation/Nonnull.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/annotation/Nonnull.java index 0bca33fc0..53e8b9662 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/annotation/Nonnull.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/annotation/Nonnull.java @@ -5,19 +5,19 @@ import javax.annotation.meta.TypeQualifier; /** - * The Java Platform Module System in Java 9 makes it hard access the javax.annotation.* - * annotations, because they live in a dependency but end up inside a split package through the - * java.xml.ws.annotation module. The latter is slated to be removed, but it hasn't happened yet in - * Java 9. + * The Java Platform Module System in Java 9 makes it hard access the javax.annotation.* annotations, because they live + * in a dependency but end up inside a split package through the java.xml.ws.annotation module. The latter is slated to + * be removed, but it hasn't happened yet in Java 9. * - *

Adding javax.annotation.Nonnull to a class works fine, but accessing it with reflection causes - * NoClassDefFoundErrors. + *

+ * Adding javax.annotation.Nonnull to a class works fine, but accessing it with reflection causes NoClassDefFoundErrors. * - *

This annotation can be used in tests to replace the regular javax.annotation.Nonnull. + *

+ * This annotation can be used in tests to replace the regular javax.annotation.Nonnull. * - *

For more info, see https://blog.codefx.org/java/jsr-305-java-9/ + *

+ * For more info, see https://blog.codefx.org/java/jsr-305-java-9/ */ @TypeQualifier @Retention(RetentionPolicy.RUNTIME) -public @interface Nonnull { -} +public @interface Nonnull {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/Embeddable.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/Embeddable.java index 9dec036b3..cc34d35d6 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/Embeddable.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/Embeddable.java @@ -7,5 +7,4 @@ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) -public @interface Embeddable { -} +public @interface Embeddable {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/EmbeddedId.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/EmbeddedId.java index 0b04e3b50..a1265db31 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/EmbeddedId.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/EmbeddedId.java @@ -7,5 +7,4 @@ @Target({ ElementType.METHOD, ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) -public @interface EmbeddedId { -} +public @interface EmbeddedId {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/Entity.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/Entity.java index 04430fd2a..fbe06b78a 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/Entity.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/Entity.java @@ -7,5 +7,4 @@ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) -public @interface Entity { -} +public @interface Entity {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/FetchType.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/FetchType.java index a52968366..74756f3f4 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/FetchType.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/FetchType.java @@ -1,6 +1,5 @@ package nl.jqno.equalsverifier.testhelpers.annotations.javax.persistence; public enum FetchType { - LAZY, - EAGER + LAZY, EAGER } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/GeneratedValue.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/GeneratedValue.java index ae6fa4d7d..f1f930f4b 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/GeneratedValue.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/GeneratedValue.java @@ -7,5 +7,4 @@ @Target({ ElementType.METHOD, ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) -public @interface GeneratedValue { -} +public @interface GeneratedValue {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/Id.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/Id.java index 4a5973ceb..11f8c2a78 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/Id.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/Id.java @@ -7,5 +7,4 @@ @Target({ ElementType.METHOD, ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) -public @interface Id { -} +public @interface Id {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/MappedSuperclass.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/MappedSuperclass.java index be2365319..c2d99ae7f 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/MappedSuperclass.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/MappedSuperclass.java @@ -7,5 +7,4 @@ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) -public @interface MappedSuperclass { -} +public @interface MappedSuperclass {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/Transient.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/Transient.java index 0c14ab231..d47bdc20d 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/Transient.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/javax/persistence/Transient.java @@ -7,5 +7,4 @@ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) -public @interface Transient { -} +public @interface Transient {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/org/eclipse/jdt/annotation/NonNullByDefault.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/org/eclipse/jdt/annotation/NonNullByDefault.java index af9733b4a..82163ccc0 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/org/eclipse/jdt/annotation/NonNullByDefault.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/org/eclipse/jdt/annotation/NonNullByDefault.java @@ -3,12 +3,11 @@ import java.lang.annotation.*; /** - * This annotation serves as a placeholder for the real {@link - * org.eclipse.jdt.annotation.NonNullByDefault} annotation. However, since that annotation is - * compiled for Java 8, and this code base must support Java 6, we use this copy instead. + * This annotation serves as a placeholder for the real {@link org.eclipse.jdt.annotation.NonNullByDefault} annotation. + * However, since that annotation is compiled for Java 8, and this code base must support Java 6, we use this copy + * instead. */ @Documented @Retention(RetentionPolicy.CLASS) @Target({ ElementType.PACKAGE, ElementType.TYPE }) -public @interface NonNullByDefault { -} +public @interface NonNullByDefault {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/org/hibernate/annotations/NaturalId.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/org/hibernate/annotations/NaturalId.java index c6429d5cf..0f7ec95b3 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/org/hibernate/annotations/NaturalId.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/org/hibernate/annotations/NaturalId.java @@ -7,5 +7,4 @@ @Target({ ElementType.METHOD, ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) -public @interface NaturalId { -} +public @interface NaturalId {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/org/jspecify/annotations/NullMarked.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/org/jspecify/annotations/NullMarked.java index f4ddb5ae0..2d2522b51 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/org/jspecify/annotations/NullMarked.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/org/jspecify/annotations/NullMarked.java @@ -3,11 +3,9 @@ import java.lang.annotation.*; /** - * This annotation serves as a placeholder for the real {@link org.jspecify.annotations.NullMarked} - * annotation. However, since that annotation is compiled for Java 9, and this code base must - * support Java 8, we use this copy instead. + * This annotation serves as a placeholder for the real {@link org.jspecify.annotations.NullMarked} annotation. However, + * since that annotation is compiled for Java 9, and this code base must support Java 8, we use this copy instead. */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.PACKAGE, ElementType.TYPE }) -public @interface NullMarked { -} +public @interface NullMarked {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/org/jspecify/annotations/Nullable.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/org/jspecify/annotations/Nullable.java index 1c27e15d2..8ac22a85f 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/org/jspecify/annotations/Nullable.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/org/jspecify/annotations/Nullable.java @@ -4,5 +4,4 @@ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE_USE) -public @interface Nullable { -} +public @interface Nullable {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/org/springframework/lang/NonNullFields.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/org/springframework/lang/NonNullFields.java index bdd65d987..31940ab37 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/org/springframework/lang/NonNullFields.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/annotations/org/springframework/lang/NonNullFields.java @@ -4,5 +4,4 @@ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PACKAGE) -public @interface NonNullFields { -} +public @interface NonNullFields {} diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/packages/subclasses/subpackage/SubA3.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/packages/subclasses/subpackage/SubA3.java index 4b2bb06f8..5078dca29 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/packages/subclasses/subpackage/SubA3.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/packages/subclasses/subpackage/SubA3.java @@ -1,6 +1,7 @@ package nl.jqno.equalsverifier.testhelpers.packages.subclasses.subpackage; import java.util.Objects; + import nl.jqno.equalsverifier.testhelpers.packages.subclasses.SuperA; public final class SubA3 extends SuperA { diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/types/Color.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/types/Color.java index 9d0e05e88..6fa3beb8e 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/types/Color.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/types/Color.java @@ -1,7 +1,5 @@ package nl.jqno.equalsverifier.testhelpers.types; public enum Color { - YELLOW, - BLUE, - INDIGO + YELLOW, BLUE, INDIGO } diff --git a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/types/TypeHelper.java b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/types/TypeHelper.java index d953a9294..cc19bbe3e 100644 --- a/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/types/TypeHelper.java +++ b/equalsverifier-core/src/test/java/nl/jqno/equalsverifier/testhelpers/types/TypeHelper.java @@ -7,6 +7,7 @@ import java.util.Arrays; import java.util.List; import java.util.Objects; + import nl.jqno.equalsverifier.testhelpers.annotations.*; public class TypeHelper { @@ -14,8 +15,7 @@ public class TypeHelper { private static final Object OBJECT = new Object(); public enum Enum { - FIRST, - SECOND + FIRST, SECOND } public static final class AllTypesContainer { @@ -65,10 +65,8 @@ public boolean equals(Object obj) { result &= _Boolean == other._Boolean; result &= Objects.equals(_Byte, other._Byte); result &= _Char == other._Char; - result &= - _Double == null ? other._Double == null : Double.compare(_Double, other._Double) == 0; - result &= - _Float == null ? other._Float == null : Float.compare(_Float, other._Float) == 0; + result &= _Double == null ? other._Double == null : Double.compare(_Double, other._Double) == 0; + result &= _Float == null ? other._Float == null : Float.compare(_Float, other._Float) == 0; result &= Objects.equals(_Int, other._Int); result &= Objects.equals(_Long, other._Long); result &= Objects.equals(_Short, other._Short); @@ -156,8 +154,7 @@ public static class DifferentAccessModifiersFieldContainer { } @SuppressWarnings("unused") - public static class DifferentAccessModifiersSubFieldContainer - extends DifferentAccessModifiersFieldContainer { + public static class DifferentAccessModifiersSubFieldContainer extends DifferentAccessModifiersFieldContainer { public final String d = ""; protected final String c = ""; @@ -286,8 +283,7 @@ public static class NoFieldsSubWithFields extends NoFields { } public enum TwoElementEnum { - ONE, - TWO + ONE, TWO } public enum OneElementEnum { @@ -316,9 +312,8 @@ public static final class SingleGenericContainerContainer { private final SingleGenericContainer integer; public SingleGenericContainerContainer( - SingleGenericContainer string, - SingleGenericContainer integer - ) { + SingleGenericContainer string, + SingleGenericContainer integer) { this.string = string; this.integer = integer; } @@ -366,9 +361,8 @@ public static final class DoubleGenericContainerContainer { private final DoubleGenericContainer integerByte; public DoubleGenericContainerContainer( - DoubleGenericContainer stringBoolean, - DoubleGenericContainer integerByte - ) { + DoubleGenericContainer stringBoolean, + DoubleGenericContainer integerByte) { this.stringBoolean = stringBoolean; this.integerByte = integerByte; } @@ -390,8 +384,7 @@ public int hashCode() { @SuppressWarnings("unused") public static final class DoubleGenericContainer { - private final DoubleGenericContainer justToMakeItRecursiveAndForcePrefabValues = - null; + private final DoubleGenericContainer justToMakeItRecursiveAndForcePrefabValues = null; private final T t; private final U u; diff --git a/equalsverifier-release-verify/src/test/java/nl/jqno/equalsverifier/verify_release/jar/helper/JarAsserter.java b/equalsverifier-release-verify/src/test/java/nl/jqno/equalsverifier/verify_release/jar/helper/JarAsserter.java index 3c21c6a96..dd14c2f8c 100644 --- a/equalsverifier-release-verify/src/test/java/nl/jqno/equalsverifier/verify_release/jar/helper/JarAsserter.java +++ b/equalsverifier-release-verify/src/test/java/nl/jqno/equalsverifier/verify_release/jar/helper/JarAsserter.java @@ -8,6 +8,7 @@ import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; + import org.junit.jupiter.api.function.Executable; public class JarAsserter { @@ -24,66 +25,45 @@ public void assertPresenceOfCoreClasses() { assertPresenceOf( EV + "/EqualsVerifier.class", EV + "/internal/reflection/ClassProbe.class", - EV + "/internal/checkers/HierarchyChecker.class" - ); + EV + "/internal/checkers/HierarchyChecker.class"); } public void assertPresenceOfMultiReleaseClasses() { assertPresenceOf( "/META-INF/versions/11" + EV + "/internal/reflection/ModuleHelper.class", "/META-INF/versions/16" + EV + "/internal/reflection/RecordsHelper.class", - "/META-INF/versions/17" + EV + "/internal/reflection/SealedTypesHelper.class" - ); + "/META-INF/versions/17" + EV + "/internal/reflection/SealedTypesHelper.class"); } public void assertPresenceOfEmbeddedDepedencies() { assertPresenceOf( EV + "/internal/lib/bytebuddy/ByteBuddy.class", - EV + "/internal/lib/objenesis/Objenesis.class" - ); + EV + "/internal/lib/objenesis/Objenesis.class"); } public void assertAbsenceOfEmbeddedDepedencies() { - assertAbsenceOf( - EV + "/internal/lib/bytebuddy/ByteBuddy.class", - EV + "/internal/lib/objenesis/Objenesis.class" - ); + assertAbsenceOf(EV + "/internal/lib/bytebuddy/ByteBuddy.class", EV + "/internal/lib/objenesis/Objenesis.class"); } public void assertPresenceOf(String... filenames) { var entries = reader.getEntries(); assertForAll( entries::contains, - fn -> - "Expected presence of: " + - fn + - ", but it was absent.\nFilename: " + - reader.getFilename(), - filenames - ); + fn -> "Expected presence of: " + fn + ", but it was absent.\nFilename: " + reader.getFilename(), + filenames); } public void assertAbsenceOf(String... fileNames) { var entries = reader.getEntries(); assertForAll( fn -> !entries.contains(fn), - fn -> - "Expected absence of: " + - fn + - ", but it was present.\nFilename: " + - reader.getFilename(), - fileNames - ); + fn -> "Expected absence of: " + fn + ", but it was present.\nFilename: " + reader.getFilename(), + fileNames); } - private void assertForAll( - Predicate assertion, - Function message, - String... filenames - ) { - Stream assertions = Arrays - .stream(filenames) - .map(fn -> () -> assertTrue(assertion.test(fn), message.apply(fn))); + private void assertForAll(Predicate assertion, Function message, String... filenames) { + Stream assertions = + Arrays.stream(filenames).map(fn -> () -> assertTrue(assertion.test(fn), message.apply(fn))); assertAll(assertions); } @@ -91,44 +71,32 @@ public void assertContentOfManifest(String implementationTitle) { var filename = "/META-INF/MANIFEST.MF"; var manifest = new String(reader.getContentOf(filename)); assertAll( - () -> - assertContains("Automatic-Module-Name: nl.jqno.equalsverifier", manifest, filename), - () -> - assertContains("Implementation-Title: " + implementationTitle, manifest, filename), + () -> assertContains("Automatic-Module-Name: nl.jqno.equalsverifier", manifest, filename), + () -> assertContains("Implementation-Title: " + implementationTitle, manifest, filename), () -> assertContains("Implementation-Version: ", manifest, filename), () -> assertContains("Multi-Release: true", manifest, filename), - () -> assertContains("Website: https://www.jqno.nl/equalsverifier", manifest, filename) - ); + () -> assertContains("Website: https://www.jqno.nl/equalsverifier", manifest, filename)); } private void assertContains(String needle, String haystack, String innerFilename) { - assertTrue( - haystack.contains(needle), - "Expected to find '" + needle + "' in " + innerFilename - ); + assertTrue(haystack.contains(needle), "Expected to find '" + needle + "' in " + innerFilename); } public void assertVersionsOfClassFiles() { assertAll( () -> assertVersionOfClassFile(52, EV + "/EqualsVerifier.class"), - () -> - assertVersionOfClassFile( - 60, - "/META-INF/versions/16" + EV + "/internal/reflection/RecordsHelper.class" - ), - () -> - assertVersionOfClassFile( - 61, - "/META-INF/versions/17" + EV + "/internal/reflection/SealedTypesHelper.class" - ) - ); + () -> assertVersionOfClassFile( + 60, + "/META-INF/versions/16" + EV + "/internal/reflection/RecordsHelper.class"), + () -> assertVersionOfClassFile( + 61, + "/META-INF/versions/17" + EV + "/internal/reflection/SealedTypesHelper.class")); } public void assertVersionsOfEmbeddedClassFiles() { assertAll( () -> assertVersionOfClassFile(49, EV + "/internal/lib/bytebuddy/ByteBuddy.class"), - () -> assertVersionOfClassFile(52, EV + "/internal/lib/objenesis/Objenesis.class") - ); + () -> assertVersionOfClassFile(52, EV + "/internal/lib/objenesis/Objenesis.class")); } private void assertVersionOfClassFile(int expectedVersion, String innerFilename) { @@ -137,12 +105,7 @@ private void assertVersionOfClassFile(int expectedVersion, String innerFilename) assertEquals( (byte) expectedVersion, actualVersion, - "Expected " + - innerFilename + - " to have version " + - expectedVersion + - ", but it has version " + - actualVersion - ); + "Expected " + innerFilename + " to have version " + expectedVersion + ", but it has version " + + actualVersion); } } diff --git a/equalsverifier-release-verify/src/test/java/nl/jqno/equalsverifier/verify_release/jar/helper/JarReader.java b/equalsverifier-release-verify/src/test/java/nl/jqno/equalsverifier/verify_release/jar/helper/JarReader.java index 5e1ef9a57..ac8418144 100644 --- a/equalsverifier-release-verify/src/test/java/nl/jqno/equalsverifier/verify_release/jar/helper/JarReader.java +++ b/equalsverifier-release-verify/src/test/java/nl/jqno/equalsverifier/verify_release/jar/helper/JarReader.java @@ -44,7 +44,8 @@ public byte[] getContentOf(String innerFilename) { try (var out = new ByteArrayOutputStream()) { Files.copy(path, out); return out.toByteArray(); - } catch (IOException e) { + } + catch (IOException e) { throw new AssertionError("Failed to read " + innerFilename + " from " + filename, e); } } @@ -54,7 +55,8 @@ private FileSystem getFileSystem() { try { var uri = URI.create("jar:" + file.toURI().toString()); return FileSystems.newFileSystem(uri, Map.of()); - } catch (IOException | URISyntaxException e) { + } + catch (IOException | URISyntaxException e) { throw new AssertionError("Failed to read " + filename, e); } } @@ -62,11 +64,9 @@ private FileSystem getFileSystem() { private Set buildEntryList() { var path = fs.getPath("/"); try (var walk = Files.walk(path)) { - return StreamSupport - .stream(walk.spliterator(), false) - .map(Path::toString) - .collect(Collectors.toSet()); - } catch (IOException e) { + return StreamSupport.stream(walk.spliterator(), false).map(Path::toString).collect(Collectors.toSet()); + } + catch (IOException e) { throw new AssertionError("Failed to read files from " + filename, e); } } diff --git a/equalsverifier-release-verify/src/test/java/nl/jqno/equalsverifier/verify_release/pom/MainPomTest.java b/equalsverifier-release-verify/src/test/java/nl/jqno/equalsverifier/verify_release/pom/MainPomTest.java index e1b724b5b..579159802 100644 --- a/equalsverifier-release-verify/src/test/java/nl/jqno/equalsverifier/verify_release/pom/MainPomTest.java +++ b/equalsverifier-release-verify/src/test/java/nl/jqno/equalsverifier/verify_release/pom/MainPomTest.java @@ -37,7 +37,6 @@ public void dependencies() { () -> pom.assertDependencyIsOptional(3), () -> pom.assertDependencyIsOptional(4), () -> pom.assertDependency(5, "org.objenesis", "objenesis"), - () -> pom.assertDependency(6, "net.bytebuddy", "byte-buddy") - ); + () -> pom.assertDependency(6, "net.bytebuddy", "byte-buddy")); } } diff --git a/equalsverifier-release-verify/src/test/java/nl/jqno/equalsverifier/verify_release/pom/helper/PomAsserter.java b/equalsverifier-release-verify/src/test/java/nl/jqno/equalsverifier/verify_release/pom/helper/PomAsserter.java index 3019b3f8f..5ad862496 100644 --- a/equalsverifier-release-verify/src/test/java/nl/jqno/equalsverifier/verify_release/pom/helper/PomAsserter.java +++ b/equalsverifier-release-verify/src/test/java/nl/jqno/equalsverifier/verify_release/pom/helper/PomAsserter.java @@ -15,29 +15,15 @@ public void assertCommonProperties() { () -> reader.assertNode("/project/groupId", "nl.jqno.equalsverifier"), () -> reader.assertNode("/project/url", "https://www.jqno.nl/equalsverifier"), () -> reader.assertNode("/project/inceptionYear", "2009"), - () -> - reader.assertNode( - "/project/licenses/license[1]/name", - "Apache License, Version 2.0" - ), + () -> reader.assertNode("/project/licenses/license[1]/name", "Apache License, Version 2.0"), () -> reader.assertNode("/project/developers/developer[1]/name", "Jan Ouwens"), - () -> - reader.assertNode( - "/project/mailingLists/mailingList[1]/archive", - "https://groups.google.com/group/equalsverifier" - ), + () -> reader + .assertNode( + "/project/mailingLists/mailingList[1]/archive", + "https://groups.google.com/group/equalsverifier"), () -> reader.assertNode("/project/scm/url", "https://github.com/jqno/equalsverifier"), - () -> - reader.assertNode( - "/project/issueManagement/url", - "https://github.com/jqno/equalsverifier/issues" - ), - () -> - reader.assertNode( - "/project/ciManagement/url", - "https://github.com/jqno/equalsverifier/actions" - ) - ); + () -> reader.assertNode("/project/issueManagement/url", "https://github.com/jqno/equalsverifier/issues"), + () -> reader.assertNode("/project/ciManagement/url", "https://github.com/jqno/equalsverifier/actions")); } public void assertArtifactId(String artifactId) { @@ -53,15 +39,13 @@ public void assertDependency(int idx, String groupId, String artifactId) { assertAll( () -> reader.assertNode(prefix + "/groupId", groupId), () -> reader.assertNode(prefix + "/artifactId", artifactId), - () -> reader.assertNode(prefix + "/scope", "compile") - ); + () -> reader.assertNode(prefix + "/scope", "compile")); } public void assertDependencyIsOptional(int idx) { var prefix = "/project/dependencies/dependency[" + idx + "]"; assertAll( () -> reader.assertNode(prefix + "/optional", "true"), - () -> reader.assertNode(prefix + "/scope", "provided") - ); + () -> reader.assertNode(prefix + "/scope", "provided")); } } diff --git a/equalsverifier-release-verify/src/test/java/nl/jqno/equalsverifier/verify_release/pom/helper/PomReader.java b/equalsverifier-release-verify/src/test/java/nl/jqno/equalsverifier/verify_release/pom/helper/PomReader.java index 461085329..357aa4f4c 100644 --- a/equalsverifier-release-verify/src/test/java/nl/jqno/equalsverifier/verify_release/pom/helper/PomReader.java +++ b/equalsverifier-release-verify/src/test/java/nl/jqno/equalsverifier/verify_release/pom/helper/PomReader.java @@ -8,6 +8,7 @@ import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathException; import javax.xml.xpath.XPathFactory; + import org.w3c.dom.Document; import org.w3c.dom.NodeList; @@ -33,16 +34,8 @@ public void assertNode(String expression, String value) { assertEquals( value, actual, - "Expected: " + - value + - ", but was: " + - actual + - "\nFilename: " + - filename + - "; expression: [" + - expression + - "]" - ); + "Expected: " + value + ", but was: " + actual + "\nFilename: " + filename + "; expression: [" + expression + + "]"); } public void assertNodeSize(int expectedLength, String expression) { @@ -50,27 +43,17 @@ public void assertNodeSize(int expectedLength, String expression) { assertEquals( expectedLength, nodes.getLength(), - "Expected node to have " + - expectedLength + - " nodes, but it has " + - nodes.getLength() + - "!\nFilename: " + - filename + - "; expression: [" + - expression + - "]" - ); + "Expected node to have " + expectedLength + " nodes, but it has " + nodes.getLength() + "!\nFilename: " + + filename + "; expression: [" + expression + "]"); } private Object getValue(String expression, QName qname) { try { var expr = xpath.compile(expression); return expr.evaluate(doc, qname); - } catch (XPathException e) { - throw new AssertionError( - "Failed to parse " + filename + " with expression [" + expression + "]", - e - ); + } + catch (XPathException e) { + throw new AssertionError("Failed to parse " + filename + " with expression [" + expression + "]", e); } } } diff --git a/pom.xml b/pom.xml index 2e026cb87..17adc10c2 100644 --- a/pom.xml +++ b/pom.xml @@ -66,9 +66,11 @@ ${argline.module} ${argline.preview} ${argline.experimental} 0.95 - checkstyle-config.xml + build/checkstyle-config.xml Max Low + build/eclipse-formatter-config.xml + build/eclipse-formatter-config.importorder 1.15.10 3.4 @@ -107,8 +109,7 @@ 1.17.2 4.8.6.6 4.8.6 - 0.22 - 2.4.0 + 2.43.0 @@ -301,16 +302,21 @@ - com.hubspot.maven.plugins - prettier-maven-plugin - ${version.prettier.maven} + com.diffplug.spotless + spotless-maven-plugin + ${version.spotless} - ${version.prettier-java.maven} - 21.7.2 + + + ${analysis.spotless.importorder.config} + + + ${analysis.spotless.formatter.config} + + - validate check