GeezerVison is showing github.com — Add hasPermittedSubclasses for Class assertions by pbacz · Pull Request #3316 · assertj/assertj
Add hasPermittedSubclasses for Class assertions
#3316
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Uh oh!
There was an error while loading. Please reload this page.
Show file tree
Hide file tree
Changes from all commits
Commits
File filter
Filter by extension
.java
(6)
All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
There are no files selected for viewing
Original file line number
Diff line number
Diff line change
Expand Up
@@ -34,6 +34,7 @@
import static org.assertj.core.error.ShouldHaveNoPackage.shouldHaveNoPackage;
import static org.assertj.core.error.ShouldHaveNoSuperclass.shouldHaveNoSuperclass;
import static org.assertj.core.error.ShouldHavePackage.shouldHavePackage;
import static org.assertj.core.error.ShouldHavePermittedSubclasses.shouldHavePermittedSubclasses;
import static org.assertj.core.error.ShouldHaveRecordComponents.shouldHaveRecordComponents;
import static org.assertj.core.error.ShouldHaveSuperclass.shouldHaveSuperclass;
import static org.assertj.core.error.ShouldNotBeNull.shouldNotBeNull;
Expand All
@@ -45,6 +46,7 @@
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import org.assertj.core.internal.Classes;
Expand Down
Expand Up
@@ -1166,6 +1168,62 @@ private static boolean isSealed(Class<?> actual) {
}
}
/**
* Verifies that permitted subclasses of the actual {@code Class} has the given {@code Class}es.
* <p>
* Example:
* <pre><code class='java'> sealed class SuperClass permits Permitted {
* }
*
* final class Permitted extends SuperClass {
* }
*
* final class NotPermitted {
* }
*
* // these assertions succeed:
* assertThat(SuperClass.class).hasPermittedSubclasses();
* assertThat(SuperClass.class).hasPermittedSubclasses(Permitted.class);
*
* // these assertions fail:
* assertThat(SuperClass.class).hasPermittedSubclasses(NotPermitted.class);
* assertThat(SuperClass.class).hasPermittedSubclasses(Permitted.class, NotPermitted.class);</code></pre>
*
* @param permittedSubclasses classes that must be permitted subclasses of the given class
* @return {@code this} assertions object
* @throws AssertionError if {@code actual} is {@code null}.
* @throws AssertionError if the actual {@code Class} does not have all of given permitted subclasses
*/
public SELF hasPermittedSubclasses(Class<?>... permittedSubclasses) {
isNotNull();
assertHasPermittedSubclasses(permittedSubclasses);
return myself;
}
private void assertHasPermittedSubclasses(Class<?>[] permittedSubclasses) {
Set<Class<?>> expected = newLinkedHashSet(permittedSubclasses);
Set<Class<?>> missing = new LinkedHashSet<>();
Set<Class<?>> actualPermitted = newLinkedHashSet(getPermittedSubclasses(actual));
for (Class<?> other : expected) {
classes.classParameterIsNotNull(other);
if (!actualPermitted.contains(other)) missing.add(other);
}
if (!missing.isEmpty()) throw assertionError(shouldHavePermittedSubclasses(actual, expected, missing));
}
private static Class<?>[] getPermittedSubclasses(Class<?> actual) {
try {
Method getPermittedSubclasses = Class.class.getMethod("getPermittedSubclasses");
Class<?>[] permittedSubclasses = (Class<?>[]) getPermittedSubclasses.invoke(actual);
return permittedSubclasses == null ? array() : permittedSubclasses;
} catch (NoSuchMethodException e) {
return new Class<?>[0];
} catch (ReflectiveOperationException e) {
throw new IllegalStateException(e);
}
}
/**
* Verifies that the actual {@code Class} is a primitive type.
* <p>
Expand Down
Original file line number
Diff line number
Diff line change
@@ -0,0 +1,41 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright 2012-2024 the original author or authors.
*/
package org.assertj.core.error;
import java.util.Collection;
/**
* Creates an error message indicating that an assertion that verifies that a class has permitted subclasses failed.
*/
public class ShouldHavePermittedSubclasses extends BasicErrorMessageFactory {
/**
* Creates a new <code>{@link ShouldHavePermittedSubclasses}</code>.
*
* @param actual the actual value in the failed assertion
* @param expected expected permitted subclasses for this class
* @param missing missing permitted subclasses for this class
* @return the created {@code ErrorMessageFactory}.
*/
public static ErrorMessageFactory shouldHavePermittedSubclasses(Class<?> actual,
Collection<Class<?>> expected,
Collection<Class<?>> missing) {
return new ShouldHavePermittedSubclasses(actual, expected, missing);
}
private ShouldHavePermittedSubclasses(Class<?> actual, Collection<Class<?>> expected, Collection<Class<?>> missing) {
super("%nExpecting%n %s%nto have permitted subclasses:%n %s%n" +
"but the following permitted subclasses were not found:%n %s",
actual, expected, missing);
}
}
Original file line number
Diff line number
Diff line change
Expand Up
@@ -317,6 +317,17 @@ public void assertHasPublicMethods(AssertionInfo info, Class<?> actual, String..
}
}
/**
* used to check that the class to compare is not null, in that case throws a {@link NullPointerException} with an
* explicit message.
*
* @param clazz the class to check
* @throws NullPointerException with an explicit message if the given class is null
*/
public void classParameterIsNotNull (Class <?> clazz ) {
requireNonNull (clazz , "The class to compare actual with should not be null" );
}
private static SortedSet <String > getMethodsWithModifier (Set <Method > methods , int modifier ) {
SortedSet <String > methodsWithModifier = newTreeSet ();
for (Method method : methods ) {
Expand Down
Expand Up
@@ -389,15 +400,4 @@ private static <M extends Member> Set<M> filterSyntheticMembers(M[] members) {
private static void assertNotNull (AssertionInfo info , Class <?> actual ) {
Objects .instance ().assertNotNull (info , actual );
}
/**
* used to check that the class to compare is not null, in that case throws a {@link NullPointerException} with an
* explicit message.
*
* @param clazz the date to check
* @throws NullPointerException with an explicit message if the given class is null
*/
private static void classParameterIsNotNull (Class <?> clazz ) {
requireNonNull (clazz , "The class to compare actual with should not be null" );
}
}
Original file line number
Diff line number
Diff line change
@@ -0,0 +1,47 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright 2012-2024 the original author or authors.
*/
package org.assertj.core.api.classes;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.BDDAssertions.then;
import static org.assertj.core.error.ShouldHavePermittedSubclasses.shouldHavePermittedSubclasses;
import static org.assertj.core.error.ShouldNotBeNull.shouldNotBeNull;
import static org.assertj.core.util.AssertionsUtil.expectAssertionError;
import static org.assertj.core.util.Lists.newArrayList;
class ClassAssert_hasPermittedSubclasses {
@Test
void should_fail_if_actual_is_null() {
// GIVEN
Class<?> actual = null;
// WHEN
AssertionError error = expectAssertionError(() -> assertThat(actual).hasPermittedSubclasses());
// THEN
then(error).hasMessage(shouldNotBeNull().create());
}
@Test
void should_fail_if_actual_does_not_have_permitted_subclasses() {
// WHEN
AssertionError error = expectAssertionError(() -> assertThat(Object.class).hasPermittedSubclasses(String.class));
// THEN
then(error).hasMessage(shouldHavePermittedSubclasses(Object.class,
newArrayList(String.class),
newArrayList(String.class)).create());
}
}
Original file line number
Diff line number
Diff line change
@@ -0,0 +1,48 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright 2012-2024 the original author or authors.
*/
package org.assertj.core.error;
import org.assertj.core.description.TextDescription;
import org.assertj.core.presentation.StandardRepresentation;
import org.assertj.core.util.Lists;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.BDDAssertions.then;
import static org.assertj.core.error.ShouldHavePermittedSubclasses.shouldHavePermittedSubclasses;
/**
* Tests for
* <code>{@link ShouldHavePermittedSubclasses#shouldHavePermittedSubclasses(Class, java.util.Collection, java.util.Collection)}}</code>
*/
class ShouldHavePermittedSubclasses_create_Test {
@Test
void should_create_error_message() {
// GIVEN
ErrorMessageFactory factory = shouldHavePermittedSubclasses(ShouldHavePermittedSubclasses_create_Test.class,
Lists.list(String.class,
Number.class),
Lists.list(Number.class));
// WHEN
String message = factory.create(new TextDescription("Test"), new StandardRepresentation());
// THEN
then(message).isEqualTo(String.format(
"[Test] %n"
+ "Expecting%n"
+ " org.assertj.core.error.ShouldHavePermittedSubclasses_create_Test%n"
+ "to have permitted subclasses:%n"
+ " [java.lang.String, java.lang.Number]%n"
+ "but the following permitted subclasses were not found:%n"
+ " [java.lang.Number]"));
}
}
Original file line number
Diff line number
Diff line change
Expand Up
@@ -18,12 +18,15 @@
import static org.assertj.core.error.ShouldBeRecord.shouldNotBeRecord;
import static org.assertj.core.error.ShouldBeSealed.shouldBeSealed;
import static org.assertj.core.error.ShouldBeSealed.shouldNotBeSealed;
import static org.assertj.core.error.ShouldHavePermittedSubclasses.shouldHavePermittedSubclasses;
import static org.assertj.core.error.ShouldHaveRecordComponents.shouldHaveRecordComponents;
import static org.assertj.core.util.Sets.set;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import java.util.List;
/**
* @author Louis Morgan
*/
Expand Down
Expand Up
@@ -103,6 +106,25 @@ void isSealed_should_pass_if_actual_is_sealed() {
assertThat(SealedClass.class).isSealed();
}
@Test
void hasPermittedSubclasses_should_pass_if_actual_has_permitted_subclass() {
// WHEN/THEN
assertThat(SealedClass.class).hasPermittedSubclasses(NonSealedClass.class);
Comment thread
pbacz marked this conversation as resolved.
Resolved
Uh oh!
There was an error while loading. Please reload this page.
}
@Test
void hasPermittedSubclasses_should_fail_if_actual_does_not_have_one_of_given_classes() {
// WHEN
Throwable thrown = catchThrowable(() -> assertThat(SealedClass.class).hasPermittedSubclasses(NonSealedClass.class,
String.class));
// THEN
then(thrown).isInstanceOf(AssertionError.class)
.hasMessage(shouldHavePermittedSubclasses(
SealedClass.class,
List.of(NonSealedClass.class, String.class),
List.of(String.class)).create());
}
private sealed class SealedClass permits NonSealedClass {
}
Expand Down
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.