Skip to content

Commit 38df043

Browse files
author
Victor Wang
committed
Add HasOnlyFieldsOrProperties api
1 parent c6808b2 commit 38df043

File tree

1 file changed

+41
-1
lines changed

1 file changed

+41
-1
lines changed

src/main/java/org/assertj/core/api/AbstractObjectAssert.java

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -574,7 +574,47 @@ public SELF hasFieldOrPropertyWithValue(String name, Object value) {
574574
objects.assertHasFieldOrPropertyWithValue(info, actual, name, value);
575575
return myself;
576576
}
577-
577+
/**
578+
* Asserts that the actual object has only the specified fields or properties.
579+
* <p>
580+
* Private fields are matched by default but this can be changed by calling {@link Assertions#setAllowExtractingPrivateFields(boolean) Assertions.setAllowExtractingPrivateFields(false)}.
581+
* <p>
582+
*
583+
* Example:
584+
* <pre><code class='java'> public class TolkienCharacter {
585+
*
586+
* private String name;
587+
* private int age;
588+
* // constructor omitted
589+
*
590+
* public String getName() {
591+
* return this.name;
592+
* }
593+
* }
594+
*
595+
* TolkienCharacter frodo = new TolkienCharacter("Frodo", 33);
596+
*
597+
* // assertions will pass :
598+
* assertThat(frodo).hasOnlyFieldsOrProperties("name", "age");
599+
*
600+
* // assertions will fail :
601+
* assertThat(frodo).hasOnlyFieldsOrProperties("not_exists");
602+
* assertThat(frodo).hasOnlyFieldsOrProperties(null);
603+
* assertThat(frodo).hasOnlyFieldsOrProperties("name");
604+
* // disable looking for private fields
605+
* Assertions.setAllowExtractingPrivateFields(false);
606+
* assertThat(frodo).hasOnlyFieldsOrProperties(null); </code></pre>
607+
*
608+
* @param names the field/property name list to check
609+
* @return {@code this} assertion object.
610+
* @throws AssertionError if the actual object is {@code null}.
611+
* @throws IllegalArgumentException if name is {@code null}.
612+
* @throws AssertionError if the actual object has not the given field/property
613+
*/
614+
public SELF hasOnlyFieldsOrProperties(String... names){
615+
objects.assertHasOnlyFieldsOrProperties(info, actual, names);
616+
return myself;
617+
}
578618
/**
579619
* Extracts the values of given fields/properties from the object under test into a list, this new list becoming
580620
* the object under test.

0 commit comments

Comments
 (0)