Package com.google.common.testing
Class ClassSanityTester
java.lang.Object
com.google.common.testing.ClassSanityTester
Tester that runs automated sanity tests for any given class. A typical use case is to test static
factory classes like:
interface Book {...}
public class Books {
public static Book hardcover(String title) {...}
public static Book paperback(String title) {...}
}
And all the created Book instances can be tested with:
new ClassSanityTester()
.forAllPublicStaticMethods(Books.class)
.thatReturn(Book.class)
.testEquals(); // or testNulls(), testSerializable() etc.
- Since:
- 14.0
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescription(package private) static classThrown if the test tries to invoke a static factory method to test instance methods but the factory returned null.final classRuns sanity tests against return values of static factory methods declared by a class.(package private) static classThrown if the test fails to generate two distinct non-null values of a constructor or factory parameter in order to testObject.equals(java.lang.Object)andObject.hashCode()of the declaring class.(package private) static classThrown if the test tries to invoke a constructor or static factory method but failed because the dummy value of a constructor or method parameter is unknown.private static final class -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate final MutableClassToInstanceMap<Object>private final ListMultimap<Class<?>,Object> private final NullPointerTester -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprivate static <T> TcreateInstance(Invokable<?, ? extends T> factory, List<?> args) (package private) voiddoTestEquals(Class<?> cls) (package private) voiddoTestNulls(Class<?> cls, NullPointerTester.Visibility visibility) forAllPublicStaticMethods(Class<?> cls) Returns an object responsible for performing sanity tests against the return values of all public static methods declared bycls, excluding superclasses.private static ObjectgenerateDummyArg(Parameter param, FreshValueGenerator generator) Returns dummy factory arguments that are equal toargsbut may be different instances, to be used to construct a second instance of the same equality group.getDummyArguments(Invokable<?, ?> invokable) private <T> TgetDummyValue(TypeToken<T> type) private static <T> ImmutableList<Invokable<?,? extends T>> getFactories(TypeToken<T> type) Factories with the least number of parameters are listed first.private static booleanhashCodeInsensitiveToArgReference(Invokable<?, ?> factory, List<Object> args, int i, Object alternateArg) private booleanhasInstanceMethodToTestNulls(Class<?> c, NullPointerTester.Visibility visibility) private <T> Tinstantiate(Invokable<?, ? extends T> factory) Instantiates usingfactory.(package private) <T> Tinstantiate(Class<T> cls) Instantiatesclsby invoking one of its non-private constructors or non-private static factory methods with the parameters automatically provided using dummy values.private static <T> Tprivate FreshValueGeneratorsetDefault(Class<T> type, T value) Sets the default value fortype.setDistinctValues(Class<T> type, T value1, T value2) Sets distinct values fortype, so that when a classFoois tested forObject.equals(java.lang.Object)andObject.hashCode(), and its construction requires a parameter oftype, the distinct values oftypecan be passed as parameters to createFooinstances that are unequal.voidtestEquals(Class<?> cls) private voidtestEqualsUsing(Invokable<?, ?> factory) voidTests thatclsproperly checks null on all constructor and method parameters that aren't annotated nullable (according to the rules ofNullPointerTester).private static <X extends Throwable>
voidthrowFirst(List<X> exceptions)
-
Field Details
-
BY_METHOD_NAME
-
BY_PARAMETERS
-
BY_NUMBER_OF_PARAMETERS
-
defaultValues
-
distinctValues
-
nullPointerTester
-
-
Constructor Details
-
ClassSanityTester
public ClassSanityTester()
-
-
Method Details
-
setDefault
Sets the default value fortype. The default value isn't used in testingObject.equals(java.lang.Object)because more than one sample instances are needed for testing inequality. To set distinct values for equality testing, usesetDistinctValues(java.lang.Class<T>, T, T)instead. -
setDistinctValues
Sets distinct values fortype, so that when a classFoois tested forObject.equals(java.lang.Object)andObject.hashCode(), and its construction requires a parameter oftype, the distinct values oftypecan be passed as parameters to createFooinstances that are unequal.Calling
setDistinctValues(type, v1, v2)also sets the default value fortypethat's used fortestNulls(java.lang.Class<?>).Only necessary for types where
ClassSanityTesterdoesn't already know how to create distinct values.- Returns:
- this tester instance
- Since:
- 17.0
-
testNulls
Tests thatclsproperly checks null on all constructor and method parameters that aren't annotated nullable (according to the rules ofNullPointerTester). In details:- All non-private static methods are checked such that passing null for any parameter
that's not annotated nullable should throw
NullPointerException. - If there is any non-private constructor or non-private static factory method declared by
cls, all non-private instance methods will be checked too using the instance created by invoking the constructor or static factory method. - If there is any non-private constructor or non-private static factory method declared by
cls:- Test will fail if default value for a parameter cannot be determined.
- Test will fail if the factory method returns null so testing instance methods is impossible.
- Test will fail if the constructor or factory method throws exception.
- If there is no non-private constructor or non-private static factory method declared by
cls, instance methods are skipped for nulls test. - Nulls test is not performed on method return values unless the method is a non-private
static factory method whose return type is
clsorcls's subtype.
- All non-private static methods are checked such that passing null for any parameter
that's not annotated nullable should throw
-
doTestNulls
void doTestNulls(Class<?> cls, NullPointerTester.Visibility visibility) throws ClassSanityTester.ParameterNotInstantiableException, IllegalAccessException, InvocationTargetException, ClassSanityTester.FactoryMethodReturnsNullException -
hasInstanceMethodToTestNulls
-
testEquals
Tests theObject.equals(java.lang.Object)andObject.hashCode()ofcls. In details:- The non-private constructor or non-private static factory method with the most parameters is used to construct the sample instances. In case of tie, the candidate constructors or factories are tried one after another until one can be used to construct sample instances.
- For the constructor or static factory method used to construct instances, it's checked that when equal parameters are passed, the result instance should also be equal; and vice versa.
- If a non-private constructor or non-private static factory method exists:
- Test will fail if default value for a parameter cannot be determined.
- Test will fail if the factory method returns null so testing instance methods is impossible.
- Test will fail if the constructor or factory method throws exception.
- If there is no non-private constructor or non-private static factory method declared by
cls, no test is performed. - Equality test is not performed on method return values unless the method is a non-private
static factory method whose return type is
clsorcls's subtype. - Inequality check is not performed against state mutation methods such as
List.add(E), or functional update methods such asJoiner.skipNulls().
Note that constructors taking a builder object cannot be tested effectively because semantics of builder can be arbitrarily complex. Still, a factory class can be created in the test to facilitate equality testing. For example:
public class FooTest { private static class FooFactoryForTest { public static Foo create(String a, String b, int c, boolean d) { return Foo.builder() .setA(a) .setB(b) .setC(c) .setD(d) .build(); } } public void testEquals() { new ClassSanityTester() .forAllPublicStaticMethods(FooFactoryForTest.class) .thatReturn(Foo.class) .testEquals(); } }It will test that Foo objects created by the
create(a, b, c, d)factory method with equal parameters are equal and vice versa, thus indirectly tests the builder equality. -
doTestEquals
-
instantiate
<T> T instantiate(Class<T> cls) throws ClassSanityTester.ParameterNotInstantiableException, IllegalAccessException, InvocationTargetException, ClassSanityTester.FactoryMethodReturnsNullException Instantiatesclsby invoking one of its non-private constructors or non-private static factory methods with the parameters automatically provided using dummy values.- Returns:
- The instantiated instance, or
nullif the class has no non-private constructor or factory method to be constructed. - Throws:
ClassSanityTester.ParameterNotInstantiableExceptionIllegalAccessExceptionInvocationTargetExceptionClassSanityTester.FactoryMethodReturnsNullException
-
instantiate
private <T> T instantiate(Invokable<?, ? extends T> factory) throws ClassSanityTester.ParameterNotInstantiableException, InvocationTargetException, IllegalAccessExceptionInstantiates usingfactory. Iffactoryis annotated nullable and returns null, null will be returned.- Throws:
ClassSanityTester.ParameterNotInstantiableException- if the static methods cannot be invoked because the default value of a parameter cannot be determined.IllegalAccessException- if the class isn't public or is nested inside a non-public class, preventing its methods from being accessible.InvocationTargetException- if a static method threw exception.
-
forAllPublicStaticMethods
Returns an object responsible for performing sanity tests against the return values of all public static methods declared bycls, excluding superclasses. -
testEqualsUsing
private void testEqualsUsing(Invokable<?, ?> factory) throws ClassSanityTester.ParameterNotInstantiableException, ClassSanityTester.ParameterHasNoDistinctValueException, IllegalAccessException, InvocationTargetException, ClassSanityTester.FactoryMethodReturnsNullException -
generateEqualFactoryArguments
private List<Object> generateEqualFactoryArguments(Invokable<?, ?> factory, List<Parameter> params, List<Object> args) throws ClassSanityTester.ParameterNotInstantiableException, ClassSanityTester.FactoryMethodReturnsNullException, InvocationTargetException, IllegalAccessExceptionReturns dummy factory arguments that are equal toargsbut may be different instances, to be used to construct a second instance of the same equality group. -
hashCodeInsensitiveToArgReference
private static boolean hashCodeInsensitiveToArgReference(Invokable<?, ?> factory, List<Object> args, int i, Object alternateArg) throws ClassSanityTester.FactoryMethodReturnsNullException, InvocationTargetException, IllegalAccessException -
newFreshValueGenerator
-
generateDummyArg
private static Object generateDummyArg(Parameter param, FreshValueGenerator generator) throws ClassSanityTester.ParameterNotInstantiableException -
throwFirst
- Throws:
X extends Throwable
-
getFactories
Factories with the least number of parameters are listed first. -
getDummyArguments
private List<Object> getDummyArguments(Invokable<?, ?> invokable) throws ClassSanityTester.ParameterNotInstantiableException -
getDummyValue
-
createInstance
private static <T> T createInstance(Invokable<?, ? extends T> factory, List<?> args) throws ClassSanityTester.FactoryMethodReturnsNullException, InvocationTargetException, IllegalAccessException -
invoke
private static <T> T invoke(Invokable<?, ? extends T> factory, List<?> args) throws InvocationTargetException, IllegalAccessException
-