Class Subject
- java.lang.Object
-
- com.google.common.truth.Subject
-
- Direct Known Subclasses:
BooleanSubject,ClassSubject,ComparableSubject,GuavaOptionalSubject,IntStreamSubject,IterableSubject,LiteProtoSubject,LongStreamSubject,MapSubject,MultimapSubject,ObjectArraySubject,OptionalDoubleSubject,OptionalIntSubject,OptionalLongSubject,OptionalSubject,PathSubject,PrimitiveBooleanArraySubject,PrimitiveByteArraySubject,PrimitiveCharArraySubject,PrimitiveDoubleArraySubject,PrimitiveFloatArraySubject,PrimitiveIntArraySubject,PrimitiveLongArraySubject,PrimitiveShortArraySubject,Re2jSubjects.Re2jStringSubject,StreamSubject,TableSubject,ThrowableSubject
public class Subject extends Object
An 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 static interfaceSubject.Factory<SubjectT extends Subject,ActualT>
-
Constructor Summary
Constructors Modifier Constructor Description protectedSubject(FailureMetadata metadata, @Nullable Object actual)The constructor is for use by subclasses only.
-
Method Summary
All Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description protected StringactualCustomStringRepresentation()Returns a string representation of the actual value for inclusion in failure messages.protected StandardSubjectBuildercheck(String format, @Nullable Object... args)Returns a builder for creating a derived subject.booleanequals(@Nullable Object other)Deprecated.Object.equals(Object)is not supported on Truth subjects.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.protected voidfailWithActual(String key, @Nullable Object value)Fails, reporting a message with two "facts": key: value but was: actual value.protected voidfailWithoutActual(Fact first, Fact... rest)Fails, reporting a message with the given facts, without automatically adding the actual value.inthashCode()Deprecated.Object.hashCode()is not supported on Truth subjects.protected StandardSubjectBuilderignoreCheck()Begins a new call chain that ignores any failures.voidisAnyOf(@Nullable Object first, @Nullable Object second, @Nullable Object @Nullable ... rest)Checks that the value under test is equal to any of the given elements.voidisEqualTo(@Nullable Object expected)Checks that the value under test is equal to the given object.voidisIn(@Nullable Iterable<?> iterable)Checks that the value under test is equal to any element in the given iterable.voidisInstanceOf(@Nullable Class<?> clazz)Checks that the value under test is an instance of the given class.voidisNoneOf(@Nullable Object first, @Nullable Object second, @Nullable Object @Nullable ... rest)Checks that the value under test is not equal to any of the given elements.voidisNotEqualTo(@Nullable Object other)Checks that the value under test is not equal to the given object.voidisNotIn(@Nullable Iterable<?> iterable)Checks that the value under test is not equal to any element in the given iterable.voidisNotInstanceOf(@Nullable Class<?> clazz)Checks that the value under test is not an instance of the given class.voidisNotNull()Checks that the value under test is not null.voidisNotSameInstanceAs(@Nullable Object other)Checks that the value under test is not the same instance as the given object.voidisNull()Checks that the value under test is null.voidisSameInstanceAs(@Nullable Object expected)Checks that the value under test is the same instance as the given object.StringtoString()Deprecated.Object.toString()is not supported on Truth subjects.
-
-
-
Constructor Detail
-
Subject
protected Subject(FailureMetadata metadata, @Nullable Object actual)
The constructor is for use by subclasses only. If you want to create an instance of this class itself, callcheck(...).that(actual).
-
-
Method Detail
-
isNull
public void isNull()
Checks that the value under test is null.
-
isNotNull
public void isNotNull()
Checks that the value under test is not null.Kotlin users: A call to
assertThat(foo).isNotNull()does not perform a smart cast onfoo. If you require a smart cast, consider usingfoo!!orassertNotNull(foo)instead. The tradeoffs are that those will look different than any surrounding Truth assertions and that they will produce somewhat worse failure messages.
-
isEqualTo
public void isEqualTo(@Nullable Object expected)
Checks that the value under test is 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.equals(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
-
isNotEqualTo
public void isNotEqualTo(@Nullable Object other)
Checks that the value under test is not equal to the given object. The meaning of equality is the same as for theisEqualTo(java.lang.Object)method.
-
isSameInstanceAs
public final void isSameInstanceAs(@Nullable Object expected)
Checks that the value under test is the same instance as the given object.This method considers
nullto be "the same instance as"nulland not the same instance as anything else.
-
isNotSameInstanceAs
public final void isNotSameInstanceAs(@Nullable Object other)
Checks that the value under test is not the same instance as the given object.This method considers
nullto be "the same instance as"nulland not the same instance as anything else.
-
isInstanceOf
public void isInstanceOf(@Nullable Class<?> clazz)
Checks that the value under test is an instance of the given class.Kotlin users: A call to
assertThat(foo).isInstanceOf(Bar::class.java)does not perform a smart cast onfoo. If you require a smart cast, consider usingfoo as BarorassertIs<Bar>(foo)instead. The tradeoffs are that those will look different than any surrounding Truth assertions and that they will produce worse failure messages (for example, by not including the actual value, only its type).
-
isNotInstanceOf
public void isNotInstanceOf(@Nullable Class<?> clazz)
Checks that the value under test is not an instance of the given class.
-
isIn
public void isIn(@Nullable Iterable<?> iterable)
Checks that the value under test is equal to any element in the given iterable.
-
isAnyOf
public void isAnyOf(@Nullable Object first, @Nullable Object second, @Nullable Object @Nullable ... rest)
Checks that the value under test is equal to any of the given elements.
-
isNotIn
public void isNotIn(@Nullable Iterable<?> iterable)
Checks that the value under test is not equal to any element in the given iterable.
-
isNoneOf
public void isNoneOf(@Nullable Object first, @Nullable Object second, @Nullable Object @Nullable ... rest)
Checks that the value under test is not equal to any of the given elements.
-
actualCustomStringRepresentation
@ForOverride protected String actualCustomStringRepresentation()
Returns a string representation of the actual value for inclusion in failure messages.Subjects should override this with care.
By default, this method returns
String.valueOf(getActualValue())for most types. It does have some special logic for a few cases, like arrays.
-
check
protected final StandardSubjectBuilder check(String format, @Nullable 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
-
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(java.lang.String, java.lang.Object...)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(String key, @Nullable 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).Note: While Truth's
fail*()methods usually throwAssertionError, they do not do so in all cases: When users use an alternativeFailureStrategy, such asExpect, thefail*()methods may instead record the failure somewhere and then return. To accommodate this,Subjectmethods should typicallyreturnafter calling afail*()method, rather than continue onward to potentially fail a second time or throw an exception. For cases in which a method needs to return anotherSubjectto the user, seeignoreCheck().
-
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")).Note: While Truth's
fail*()methods usually throwAssertionError, they do not do so in all cases: When users use an alternativeFailureStrategy, such asExpect, thefail*()methods may instead record the failure somewhere and then return. To accommodate this,Subjectmethods should typicallyreturnafter calling afail*()method, rather than continue onward to potentially fail a second time or throw an exception. For cases in which a method needs to return anotherSubjectto the user, seeignoreCheck().
-
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")).Note: While Truth's
fail*()methods usually throwAssertionError, they do not do so in all cases: When users use an alternativeFailureStrategy, such asExpect, thefail*()methods may instead record the failure somewhere and then return. To accommodate this,Subjectmethods should typicallyreturnafter calling afail*()method, rather than continue onward to potentially fail a second time or throw an exception. For cases in which a method needs to return anotherSubjectto the user, seeignoreCheck(). - when the actual value is obvious from the rest of the message. For example,
-
equals
@Deprecated public final boolean equals(@Nullable Object other)
Deprecated.Object.equals(Object)is not supported on Truth subjects. If you are writing a test assertion (actual vs. expected), useisEqualTo(Object)instead.- Overrides:
equalsin classObject- Throws:
UnsupportedOperationException- always
-
hashCode
@Deprecated public final int hashCode()
Deprecated.Object.hashCode()is not supported on Truth subjects.- Overrides:
hashCodein classObject- Throws:
UnsupportedOperationException- always
-
toString
@Deprecated public String toString()
Deprecated.Object.toString()is not supported on Truth subjects.- Overrides:
toStringin classObject- Throws:
UnsupportedOperationException- always
-
-