Class Subject
- java.lang.Object
-
- com.google.common.truth.Subject
-
- Direct Known Subclasses:
AbstractArraySubject,BooleanSubject,ClassSubject,ComparableSubject,GuavaOptionalSubject,IntStreamSubject,IterableSubject,LongStreamSubject,MapSubject,MultimapSubject,OptionalDoubleSubject,OptionalIntSubject,OptionalLongSubject,OptionalSubject,PathSubject,StreamSubject,TableSubject,ThrowableSubject
public class Subject extends java.lang.ObjectAn object that lets you perform checks on the value under test. For example,SubjectcontainsisEqualTo(Object)andisInstanceOf(Class), andStringSubjectcontainsstartsWith(String).To create a
Subjectinstance, most users will call anassertThatmethod. For information about other ways to create an instance, see this FAQ entry.For people extending Truth
For information about writing a custom
Subject, see our doc on extensions.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description private static classSubject.ComparisonResultThe result of comparing two objects for equality.(package private) static classSubject.EqualityCheckstatic interfaceSubject.Factory<SubjectT extends Subject,ActualT>
-
Field Summary
Fields Modifier and Type Field Description private java.lang.Objectactualprivate java.lang.StringcustomNameprivate static char[]HEX_DIGITSprivate static char[]hexDigitsprivate static FailureStrategyIGNORE_STRATEGYprivate FailureMetadatametadataprivate static com.google.common.base.Function<java.lang.Object,java.lang.Object>STRINGIFYprivate java.lang.StringtypeDescriptionOverride
-
Constructor Summary
Constructors Modifier Constructor Description protectedSubject(FailureMetadata metadata, java.lang.Object actual)Constructor for use by subclasses.(package private)Subject(FailureMetadata metadata, java.lang.Object actual, java.lang.String typeDescriptionOverride)Special constructor that lets subclasses provide a description of the type they're testing.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description (package private) java.lang.Objectactual()Returns the actual value under test.protected java.lang.StringactualCustomStringRepresentation()Supplies the direct string representation of the actual value to other methods which may prefix or otherwise position it in an error message.(package private) java.lang.StringactualCustomStringRepresentationForPackageMembersToCall()private static java.lang.StringarrayType(java.lang.Object array)private static char[]asUnicodeHexEscape(char c)private static java.lang.Stringbase16(byte[] bytes)(package private) FactbutWas()Returns a "but was:" string. (package private) StandardSubjectBuildercheck()Deprecated.Use the other overload, which requires you to supply more information to include in any failure messages.protected StandardSubjectBuildercheck(java.lang.String format, java.lang.Object... args)Returns a builder for creating a derived subject.private static Subject.ComparisonResultcheckArrayEqualsRecursive(java.lang.Object expectedArray, java.lang.Object actualArray, java.lang.String lastIndex)Returns null if the arrays are equal, recursively.private static Subject.ComparisonResultcheckByteArrayEquals(byte[] expected, byte[] actual)Returns null if the arrays are equal.(package private) StandardSubjectBuildercheckNoNeedToDisplayBothValues(java.lang.String format, java.lang.Object... args)private static booleanclassMetadataUnsupported()private Subject.ComparisonResultcompareForEquality(java.lang.Object expected)Returns whetheractualequalsexpecteddiffer and, in some cases, a description of how they differ.private StandardSubjectBuilderdoCheck(FailureMetadata.OldAndNewValuesAreSimilar valuesAreSimilar, java.lang.String format, java.lang.Object[] args)private voiddoFail(com.google.common.collect.ImmutableList<Fact> facts)private static java.util.List<java.lang.String>doubleArrayAsString(double[] items)booleanequals(java.lang.Object o)Deprecated.Object.equals(Object)is not supported on Truth subjects.private static java.lang.StringescapeWhitespace(char c)private static java.lang.StringescapeWhitespace(java.lang.String in)(package private) voidfail(java.lang.String check)Deprecated.(package private) voidfail(java.lang.String verb, java.lang.Object other)Deprecated.Prefer to constructFact-style methods, typically by usingfailWithActual(String, Object).(package private) voidfail(java.lang.String verb, java.lang.Object... messageParts)Deprecated.Prefer to constructFact-style methods, typically by usingfailWithActual(Fact, Fact...).private voidfailEqualityCheck(Subject.EqualityCheck equalityCheck, java.lang.Object expected, Subject.ComparisonResult difference)(package private) voidfailEqualityCheckForEqualsWithoutDescription(java.lang.Object expected)Special version offailEqualityCheck(com.google.common.truth.Subject.EqualityCheck, java.lang.Object, com.google.common.truth.Subject.ComparisonResult)for use fromIterableSubject, documented further there.private voidfailEqualityCheckNoComparisonFailure(Subject.ComparisonResult difference, Fact... facts)protected voidfailWithActual(Fact first, Fact... rest)Fails, reporting a message with the given facts, followed by an automatically added fact of the form: but was: actual value.(package private) voidfailWithActual(Facts facts)(package private) voidfailWithActual(java.lang.Iterable<Fact> facts)protected voidfailWithActual(java.lang.String key, java.lang.Object value)Fails, reporting a message with two "facts": key: value but was: actual value.(package private) voidfailWithBadResults(java.lang.String verb, java.lang.Object expected, java.lang.String failVerb, java.lang.Object actual)Deprecated.Prefer to constructFact-style methods, typically by usingfailWithActual(Fact, Fact...).(package private) voidfailWithCustomSubject(java.lang.String verb, java.lang.Object expected, java.lang.Object actual)Deprecated.Prefer to constructFact-style methods, typically by usingfailWithoutActual(Fact, Fact...).protected voidfailWithoutActual(Fact first, Fact... rest)Fails, reporting a message with the given facts, without automatically adding the actual value.(package private) voidfailWithoutActual(Facts facts)(package private) voidfailWithoutActual(java.lang.Iterable<Fact> facts)(package private) voidfailWithoutActual(java.lang.String check)Deprecated.(package private) voidfailWithoutSubject(java.lang.String check)Deprecated.private static java.util.List<java.lang.String>floatArrayAsString(float[] items)private java.lang.StringformatActualOrExpected(java.lang.Object o)private static booleangwtSafeObjectEquals(java.lang.Object actual, java.lang.Object expected)inthashCode()Deprecated.Object.hashCode()is not supported on Truth subjects.protected StandardSubjectBuilderignoreCheck()Begins a new call chain that ignores any failures.private static longintegralValue(java.lang.Object o)voidisAnyOf(java.lang.Object first, java.lang.Object second, java.lang.Object... rest)Fails unless the subject is equal to any of the given elements.voidisEqualTo(java.lang.Object expected)Fails if the subject is not equal to the given object.voidisIn(java.lang.Iterable<?> iterable)Fails unless the subject is equal to any element in the given iterable.voidisInstanceOf(java.lang.Class<?> clazz)Fails if the subject is not an instance of the given class.private static booleanisIntegralBoxedPrimitive(java.lang.Object o)voidisNoneOf(java.lang.Object first, java.lang.Object second, java.lang.Object... rest)Fails if the subject is equal to any of the given elements.voidisNotEqualTo(java.lang.Object unexpected)Fails if the subject is equal to the given object.voidisNotIn(java.lang.Iterable<?> iterable)Fails if the subject is equal to any element in the given iterable.voidisNotInstanceOf(java.lang.Class<?> clazz)Fails if the subject is an instance of the given class.voidisNotNull()Fails if the subject is null.voidisNotSameInstanceAs(java.lang.Object unexpected)Fails if the subject is the same instance as the given object.voidisNull()Fails if the subject is not null.voidisSameInstanceAs(java.lang.Object expected)Fails if the subject is not the same instance as the given object.private com.google.common.collect.ImmutableList<Fact>nameAsFacts()private com.google.common.collect.ImmutableList<Fact>prependNameIfAny(com.google.common.collect.ImmutableList<Fact> facts)private voidstandardIsEqualTo(java.lang.Object expected)private voidstandardIsNotEqualTo(java.lang.Object unexpected)private static java.lang.Iterable<?>stringableIterable(java.lang.Object[] array)java.lang.StringtoString()private booleantryFailForEmptyString(java.lang.Object expected)Checks whether the actual and expected values are empty strings.private booleantryFailForTrailingWhitespaceOnly(java.lang.Object expected)Checks whether the actual and expected values are strings that match except for trailing whitespace.(package private) java.lang.StringtypeDescription()private static java.lang.StringtypeDescriptionOrGuess(java.lang.Class<? extends Subject> clazz, java.lang.String typeDescriptionOverride)
-
-
-
Field Detail
-
IGNORE_STRATEGY
private static final FailureStrategy IGNORE_STRATEGY
-
metadata
private final FailureMetadata metadata
-
actual
private final java.lang.Object actual
-
customName
private java.lang.String customName
-
typeDescriptionOverride
private final java.lang.String typeDescriptionOverride
-
hexDigits
private static final char[] hexDigits
-
STRINGIFY
private static final com.google.common.base.Function<java.lang.Object,java.lang.Object> STRINGIFY
-
HEX_DIGITS
private static final char[] HEX_DIGITS
-
-
Constructor Detail
-
Subject
protected Subject(FailureMetadata metadata, java.lang.Object actual)
Constructor for use by subclasses. If you want to create an instance of this class itself, callcheck(...).that(actual).
-
Subject
Subject(FailureMetadata metadata, java.lang.Object actual, java.lang.String typeDescriptionOverride)
Special constructor that lets subclasses provide a description of the type they're testing. For example,ThrowableSubjectpasses the description "throwable." Normally, Truth is able to infer this name from the class name. However, if we lack runtime type information (notably, under j2cl with class metadata off), we might not have access to the original class name.We don't expect to make this a public API: Class names are nearly always available. It's just that we want to be able to run Truth's own tests run with class metadata off, and it's easier to tweak the subjects to know their own names rather than generalize the tests to accept obfuscated names.
-
-
Method Detail
-
isNull
public void isNull()
Fails if the subject is not null.
-
isNotNull
public void isNotNull()
Fails if the subject is null.
-
isEqualTo
public void isEqualTo(java.lang.Object expected)
Fails if the subject is not equal to the given object. For the purposes of this comparison, two objects are equal if any of the following is true:- they are equal according to
Objects.equal(java.lang.Object, java.lang.Object) - they are arrays and are considered equal by the appropriate
Arrays.equals(long[], long[])overload - they are boxed integer types (
Byte,Short,Character,Integer, orLong) and they are numerically equal when converted toLong. - the actual value is a boxed floating-point type (
DoubleorFloat), the expected value is anInteger, and the two are numerically equal when converted toDouble. (This allowsassertThat(someDouble).isEqualTo(0)to pass.)
Note: This method does not test the
Object.equals(java.lang.Object)implementation itself; it assumes that method is functioning correctly according to its contract. Testing anequalsimplementation requires a utility such as guava-testlib's EqualsTester.In some cases, this method might not even call
equals. It may instead perform other tests that will return the same result as long asequalsis implemented according to the contract for its type. - they are equal according to
-
standardIsEqualTo
private void standardIsEqualTo(java.lang.Object expected)
-
isNotEqualTo
public void isNotEqualTo(java.lang.Object unexpected)
Fails if the subject is equal to the given object. The meaning of equality is the same as for theisEqualTo(java.lang.Object)method.
-
standardIsNotEqualTo
private void standardIsNotEqualTo(java.lang.Object unexpected)
-
compareForEquality
private Subject.ComparisonResult compareForEquality(java.lang.Object expected)
Returns whetheractualequalsexpecteddiffer and, in some cases, a description of how they differ.The equality check follows the rules described on
isEqualTo(java.lang.Object).
-
isIntegralBoxedPrimitive
private static boolean isIntegralBoxedPrimitive(java.lang.Object o)
-
integralValue
private static long integralValue(java.lang.Object o)
-
isSameInstanceAs
public final void isSameInstanceAs(java.lang.Object expected)
Fails if the subject is not the same instance as the given object.
-
isNotSameInstanceAs
public final void isNotSameInstanceAs(java.lang.Object unexpected)
Fails if the subject is the same instance as the given object.
-
isInstanceOf
public void isInstanceOf(java.lang.Class<?> clazz)
Fails if the subject is not an instance of the given class.
-
isNotInstanceOf
public void isNotInstanceOf(java.lang.Class<?> clazz)
Fails if the subject is an instance of the given class.
-
isIn
public void isIn(java.lang.Iterable<?> iterable)
Fails unless the subject is equal to any element in the given iterable.
-
isAnyOf
public void isAnyOf(java.lang.Object first, java.lang.Object second, java.lang.Object... rest)Fails unless the subject is equal to any of the given elements.
-
isNotIn
public void isNotIn(java.lang.Iterable<?> iterable)
Fails if the subject is equal to any element in the given iterable.
-
isNoneOf
public void isNoneOf(java.lang.Object first, java.lang.Object second, java.lang.Object... rest)Fails if the subject is equal to any of the given elements.
-
actual
final java.lang.Object actual()
Returns the actual value under test.
-
actualCustomStringRepresentation
protected java.lang.String actualCustomStringRepresentation()
Supplies the direct string representation of the actual value to other methods which may prefix or otherwise position it in an error message. This should only be overridden to provide an improved string representation of the value under test, as it would appear in any given error message, and should not be used for additional prefixing.Subjects should override this with care.
By default, this returns
String.ValueOf(getActualValue()).
-
actualCustomStringRepresentationForPackageMembersToCall
final java.lang.String actualCustomStringRepresentationForPackageMembersToCall()
-
formatActualOrExpected
private java.lang.String formatActualOrExpected(java.lang.Object o)
-
base16
private static java.lang.String base16(byte[] bytes)
-
stringableIterable
private static java.lang.Iterable<?> stringableIterable(java.lang.Object[] array)
-
checkByteArrayEquals
private static Subject.ComparisonResult checkByteArrayEquals(byte[] expected, byte[] actual)
Returns null if the arrays are equal. If not equal, returns a string comparing the two arrays, displaying them in the style "[1, 2, 3]" to supplement the main failure message, which uses the style "010203."
-
checkArrayEqualsRecursive
private static Subject.ComparisonResult checkArrayEqualsRecursive(java.lang.Object expectedArray, java.lang.Object actualArray, java.lang.String lastIndex)
Returns null if the arrays are equal, recursively. If not equal, returns the string of the index at which they're different.
-
arrayType
private static java.lang.String arrayType(java.lang.Object array)
-
gwtSafeObjectEquals
private static boolean gwtSafeObjectEquals(java.lang.Object actual, java.lang.Object expected)
-
doubleArrayAsString
private static java.util.List<java.lang.String> doubleArrayAsString(double[] items)
-
floatArrayAsString
private static java.util.List<java.lang.String> floatArrayAsString(float[] items)
-
check
@Deprecated final StandardSubjectBuilder check()
Deprecated.Use the other overload, which requires you to supply more information to include in any failure messages.Returns a builder for creating a derived subject but without providing information about how the derived subject will relate to the current subject. In most cases, you should provide such information by using the other overload.
-
check
protected final StandardSubjectBuilder check(java.lang.String format, java.lang.Object... args)
Returns a builder for creating a derived subject.Derived subjects retain the
FailureStrategyand messages of the current subject, and in some cases, they automatically supplement their failure message with information about the original subject.For example,
ThrowableSubject.hasMessageThat(), which returns aStringSubject, is implemented withcheck("getMessage()").that(actual.getMessage()).The arguments to
checkdescribe how the new subject was derived from the old, formatted like a chained method call. This allows Truth to include that information in its failure messages. For example,assertThat(caught).hasCauseThat().hasMessageThat()will produce a failure message that includes the string "throwable.getCause().getMessage()," thanks to internalcheckcalls that supplied "getCause()" and "getMessage()" as arguments.If the method you're delegating to accepts parameters, you can pass
checka format string. For example,MultimapSubject.valuesForKey(java.lang.Object)callscheck("valuesForKey(%s)", key).If you aren't really delegating to an instance method on the actual value -- maybe you're calling a static method, or you're calling a chain of several methods -- you can supply whatever string will be most useful to users. For example, if you're delegating to
getOnlyElement(actual.colors()), you might callcheck("onlyColor()").- Parameters:
format- a template with%splaceholdersargs- the arguments to be inserted into those placeholders
-
checkNoNeedToDisplayBothValues
final StandardSubjectBuilder checkNoNeedToDisplayBothValues(java.lang.String format, java.lang.Object... args)
-
doCheck
private StandardSubjectBuilder doCheck(FailureMetadata.OldAndNewValuesAreSimilar valuesAreSimilar, java.lang.String format, java.lang.Object[] args)
-
ignoreCheck
protected final StandardSubjectBuilder ignoreCheck()
Begins a new call chain that ignores any failures. This is useful for subjects that normally delegate with to other subjects by usingcheck()but have already reported a failure. In such cases it may still be necessary to return aSubjectinstance even though any subsequent assertions are meaningless. For example, if a user chains together moreThrowableSubject.hasCauseThat()calls than the actual exception has causes,hasCauseThatreturnsignoreCheck().that(... a dummy exception ...).
-
failWithActual
protected final void failWithActual(java.lang.String key, java.lang.Object value)Fails, reporting a message with two "facts":- key: value
- but was: actual value.
This is the simplest failure API. For more advanced needs, see the other overload and
failWithoutActual.Example usage: The check
contains(String)callsfailWithActual("expected to contain", string).
-
failWithActual
protected final void failWithActual(Fact first, Fact... rest)
Fails, reporting a message with the given facts, followed by an automatically added fact of the form:- but was: actual value.
If you have only one fact to report (and it's a key-value fact), prefer the simpler overload.
Example usage: The check
isEmpty()callsfailWithActual(simpleFact("expected to be empty")).
-
failWithActual
final void failWithActual(java.lang.Iterable<Fact> facts)
-
failWithActual
final void failWithActual(Facts facts)
-
fail
@Deprecated final void fail(java.lang.String check)
Deprecated.Prefer to constructFact-style methods, typically by usingfailWithActual(simpleFact(...)). However, if you want to preserve your exact failure message as a migration aid, you can inline this method (and then inline the resulting method call, as well).Reports a failure constructing a message from a simple verb.- Parameters:
check- the check being asserted
-
fail
@Deprecated final void fail(java.lang.String verb, java.lang.Object other)Deprecated.Prefer to constructFact-style methods, typically by usingfailWithActual(String, Object). However, if you want to preserve your exact failure message as a migration aid, you can inline this method (and then inline the resulting method call, as well).Assembles a failure message and passes such to the FailureStrategy- Parameters:
verb- the check being assertedother- the value against which the subject is compared
-
fail
@Deprecated final void fail(java.lang.String verb, java.lang.Object... messageParts)Deprecated.Prefer to constructFact-style methods, typically by usingfailWithActual(Fact, Fact...). However, if you want to preserve your exact failure message as a migration aid, you can inline this method.Assembles a failure message and passes such to the FailureStrategy- Parameters:
verb- the check being assertedmessageParts- the expectations against which the subject is compared
-
failEqualityCheckForEqualsWithoutDescription
final void failEqualityCheckForEqualsWithoutDescription(java.lang.Object expected)
Special version offailEqualityCheck(com.google.common.truth.Subject.EqualityCheck, java.lang.Object, com.google.common.truth.Subject.ComparisonResult)for use fromIterableSubject, documented further there.
-
failEqualityCheck
private void failEqualityCheck(Subject.EqualityCheck equalityCheck, java.lang.Object expected, Subject.ComparisonResult difference)
-
tryFailForTrailingWhitespaceOnly
private boolean tryFailForTrailingWhitespaceOnly(java.lang.Object expected)
Checks whether the actual and expected values are strings that match except for trailing whitespace. If so, reports a failure and returns true.
-
escapeWhitespace
private static java.lang.String escapeWhitespace(java.lang.String in)
-
escapeWhitespace
private static java.lang.String escapeWhitespace(char c)
-
tryFailForEmptyString
private boolean tryFailForEmptyString(java.lang.Object expected)
Checks whether the actual and expected values are empty strings. If so, reports a failure and returns true.
-
asUnicodeHexEscape
private static char[] asUnicodeHexEscape(char c)
-
failEqualityCheckNoComparisonFailure
private void failEqualityCheckNoComparisonFailure(Subject.ComparisonResult difference, Fact... facts)
-
failWithBadResults
@Deprecated final void failWithBadResults(java.lang.String verb, java.lang.Object expected, java.lang.String failVerb, java.lang.Object actual)Deprecated.Prefer to constructFact-style methods, typically by usingfailWithActual(Fact, Fact...). However, if you want to preserve your exact failure message as a migration aid, you can inline this method.Assembles a failure message and passes it to the FailureStrategy- Parameters:
verb- the check being assertedexpected- the expectations against which the subject is comparedfailVerb- the failure of the check being assertedactual- the actual value the subject was compared against
-
failWithCustomSubject
@Deprecated final void failWithCustomSubject(java.lang.String verb, java.lang.Object expected, java.lang.Object actual)Deprecated.Prefer to constructFact-style methods, typically by usingfailWithoutActual(Fact, Fact...). However, if you want to preserve your exact failure message as a migration aid, you can inline this method.Assembles a failure message with an alternative representation of the wrapped subject and passes it to the FailureStrategy- Parameters:
verb- the check being assertedexpected- the expected value of the checkactual- the custom representation of the subject to be reported in the failure.
-
failWithoutSubject
@Deprecated final void failWithoutSubject(java.lang.String check)
Deprecated.Prefer to constructFact-style methods, typically by usingfailWithoutActual(simpleFact(...)). However, if you want to preserve your exact failure message as a migration aid, you can inline this method.
-
failWithoutActual
protected final void failWithoutActual(Fact first, Fact... rest)
Fails, reporting a message with the given facts, without automatically adding the actual value.Most failure messages should report the actual value, so most checks should call
failWithActualinstead. However,failWithoutActualis useful in some cases:- when the actual value is obvious from the rest of the message. For example,
isNotEmpty()callsfailWithoutActual(simpleFact("expected not to be empty"). - when the actual value shouldn't come last or should have a different key than the default
of "but was." For example,
isNotWithin(...).of(...)callsfailWithoutActualso that it can put the expected and actual values together, followed by the tolerance.
Example usage: The check
isEmpty()callsfailWithActual(simpleFact("expected to be empty")). - when the actual value is obvious from the rest of the message. For example,
-
failWithoutActual
final void failWithoutActual(java.lang.Iterable<Fact> facts)
-
failWithoutActual
final void failWithoutActual(Facts facts)
-
failWithoutActual
@Deprecated final void failWithoutActual(java.lang.String check)
Deprecated.Prefer to constructFact-style methods, typically by usingfailWithoutActual(simpleFact(...)). However, if you want to preserve your exact failure message as a migration aid, you can inline this method (and then inline the resulting method call, as well).Assembles a failure message without a given subject and passes it to the FailureStrategy- Parameters:
check- the check being asserted
-
equals
@Deprecated public final boolean equals(java.lang.Object o)
Deprecated.Object.equals(Object)is not supported on Truth subjects. If you meant to test object equality between an expected and the actual value, useisEqualTo(Object)instead.- Overrides:
equalsin classjava.lang.Object- Throws:
java.lang.UnsupportedOperationException- always
-
hashCode
@Deprecated public final int hashCode()
Deprecated.Object.hashCode()is not supported on Truth subjects.- Overrides:
hashCodein classjava.lang.Object- Throws:
java.lang.UnsupportedOperationException- always
-
toString
public java.lang.String toString()
- Overrides:
toStringin classjava.lang.Object
-
butWas
final Fact butWas()
Returns a "but was:" string. This method should be rarely needed, since Truth inserts a "but was" fact by default for assertions. However, it's occasionally useful for calls to failWithoutActualthat want a "but was" fact but don't want it to come last, where Truth inserts it by default.
-
typeDescription
final java.lang.String typeDescription()
-
typeDescriptionOrGuess
private static java.lang.String typeDescriptionOrGuess(java.lang.Class<? extends Subject> clazz, java.lang.String typeDescriptionOverride)
-
classMetadataUnsupported
private static boolean classMetadataUnsupported()
-
doFail
private void doFail(com.google.common.collect.ImmutableList<Fact> facts)
-
prependNameIfAny
private com.google.common.collect.ImmutableList<Fact> prependNameIfAny(com.google.common.collect.ImmutableList<Fact> facts)
-
nameAsFacts
private com.google.common.collect.ImmutableList<Fact> nameAsFacts()
-
-