Package org.powermock.reflect.internal
Class WhiteboxImpl
java.lang.Object
org.powermock.reflect.internal.WhiteboxImpl
Various utilities for accessing internals of a class. Basically a simplified
reflection utility intended for tests.
-
Field Summary
FieldsModifier and TypeFieldDescriptionprivate static ConcurrentMap
<Class, Method[]> "Strong" map prevent class and method objects from being GCed and unloaded.private static ProxyFrameworks
The proxy framework. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprivate static void
appendArgument
(StringBuilder argumentsAsString, int index, String argumentName, Object[] arguments) Append argument.(package private) static boolean
areAllArgumentsOfSameType
(Object[] arguments) Check if all arguments are of the same type.static boolean
areAllMethodsStatic
(Method... methods) Are all methods static.private static boolean
argumentTypesEqualsPrimitiveTypes
(Class<?>[] argumentTypes, Class<?>[] primitiveType) private static void
Assert object in get internal state is not null.(package private) static boolean
checkArgumentTypesMatchParameterTypes
(boolean isVarArgs, Class<?>[] parameterTypes, Object[] arguments) Check argument types match parameter types.static boolean
checkIfParameterTypesAreSame
(boolean isVarArgs, Class<?>[] expectedParameterTypes, Class<?>[] actualParameterTypes) Check if parameter types are same.private static String
concatenateStrings
(String... stringsToConcatenate) Concatenate strings.private static Class<?>[]
convertArgumentTypesToPrimitive
(Class<?>[] paramTypes, Object[] arguments) Convert argument types to primitive.private static Class<?>[]
convertParameterTypesToPrimitive
(Class<?>[] parameterTypes) Convert parameter types to primitive.private static <T> void
(package private) static void
copyState
(Object object, Object context, FieldMatchingStrategy strategy) Copy state.static <T> void
copyToMock
(T from, T mock) static <T> void
copyToRealObject
(T from, T to) private static <T> void
private static <T> void
copyValues
(T from, T mock, Class<?> classFrom) private static Object
createAndPopulateVarArgsArray
(Class<?> varArgsType, int varArgsStartPosition, Object... arguments) Creates the and populate var args array.private static <T> T
createInstance
(Constructor<T> constructor, Object... arguments) Creates the instance.(package private) static boolean
doesParameterTypesMatchForVarArgsInvocation
(boolean isVarArgs, Class<?>[] parameterTypes, Object[] arguments) Does parameter types match for var args invocation.private static Method[]
doGetAllMethods
(Class<?> clazz) private static <T> T
doInvokeMethod
(Object tested, Class<?> declaringClass, String methodToExecute, Object... arguments) Do invoke method.(package private) static Constructor<?>[]
filterPowerMockConstructor
(Constructor<?>[] declaredConstructors) Filter power mock constructor.findAllFieldsUsingStrategy
(FieldMatcherStrategy strategy, Object object, boolean checkHierarchy, boolean onlyInstanceFields, Class<?> startClass) Find all fields using strategy.static Constructor
<?> findConstructorOrThrowException
(Class<?> type) Finds and returns any constructor.static Constructor
<?> Finds and returns the default constructor.private static Field
findField
(Object object, FieldMatcherStrategy strategy, Class<?> where) Find field.private static Field
findFieldInHierarchy
(Object object, String fieldName) Find field in hierarchy.private static Field
findFieldInHierarchy
(Object object, FieldMatcherStrategy strategy) Find field in hierarchy.private static Field
findFieldOrThrowException
(Class<?> fieldType, Class<?> where) Find field or throw exception.static <T> Method
findMethod
(Class<T> type, String methodName, Class<?>... parameterTypes) Finds and returns a method based on the input parameters.static Method
findMethodOrThrowException
(Class<?> type, String methodName, Class<?>... parameterTypes) Find method or throw exception.static Method
findMethodOrThrowException
(Object tested, Class<?> declaringClass, String methodToExecute, Object[] arguments) Finds and returns a certain method.private static Field
findSingleFieldUsingStrategy
(FieldMatcherStrategy strategy, Object object, boolean checkHierarchy, Class<?> startClass) Find single field using strategy.static Constructor
<?> findUniqueConstructorOrThrowException
(Class<?> type, Object... arguments) Finds and returns a certain constructor.static Constructor<?>[]
getAllConstructors
(Class<?> clazz) Get all declared constructors in the class and set accessible totrue
.static Field[]
getAllFields
(Class<?> clazz) Get all fields in a class hierarchy! Both declared an non-declared (no duplicates).getAllInstanceFields
(Object object) Get all instance fields for a particular object.static <T> Method[]
getAllMethodExcept
(Class<T> type, String... methodNames) Gets the all method except.static Method[]
getAllMethods
(Class<?> clazz) Get all methods in a class hierarchy! Both declared an non-declared (no duplicates).static <T> Method[]
getAllMethodsExcept
(Class<T> type, String methodNameToExclude, Class<?>[] argumentTypes) Gets the all metods except.private static Method[]
getAllPublicMethods
(Class<?> clazz) Get all public methods for a class (no duplicates)! Note that the class-hierarchy will not be traversed.getAllStaticFields
(Class<?> type) Get all static fields for a particular type.getAnonymousInnerClassType
(Class<?> declaringClass, int occurrence) Get the type of an anonymous inner class.(package private) static String
getArgumentTypesAsString
(Object... arguments) Gets the argument types as string.private static <T> Constructor
<T> getBestCandidateConstructor
(Class<T> classThatContainsTheConstructorToTest, Class<?>[] argumentTypes, Object[] arguments) static Method
getBestMethodCandidate
(Class<?> cls, String methodName, Class<?>[] signature, boolean exactParameterTypeMatch) Gets the best method candidate.private static Class
<?> getComponentType
(Class<?> type) static Constructor
<?> getConstructor
(Class<?> type, Class<?>... parameterTypes) Convenience method to get a (declared) constructor from a class type without having to catch the checked exceptions otherwise required.static Field
Convenience method to get a field from a class type.private static Field
Gets the field.static Field[]
Get an array ofField
's that matches the supplied list of field names.getFieldsAnnotatedWith
(Object object, Class<? extends Annotation>[] annotationTypes) Get all fields annotated with a particular annotation.getFieldsAnnotatedWith
(Object object, Class<? extends Annotation> annotation, Class<? extends Annotation>... additionalAnnotations) Get all fields annotated with a particular annotation.getFieldsOfType
(Object object, Class<?> type) Get all fields assignable from a particular type.static Constructor
<?> getFirstParentConstructor
(Class<?> klass) Get the first parent constructor defined in a super class ofklass
.getInnerClassType
(Class<?> declaringClass, String name) Get an inner class type.static <T> T
getInternalState
(Object object, Class<T> fieldType) Get the value of a field using reflection.static <T> T
getInternalState
(Object object, Class<T> fieldType, Class<?> where) Get the value of a field using reflection.static <T> T
getInternalState
(Object object, String fieldName) Get the value of a field using reflection.static <T> T
getInternalState
(Object object, String fieldName, Class<?> where) Get the value of a field using reflection.getLocalClassType
(Class<?> declaringClass, int occurrence, String name) Get the type of a local inner class.static Method
Convenience method to get a method from a class type without having to catch the checked exceptions otherwise required.static Method
Convenience method to get a method from a class type without having to catch the checked exceptions otherwise required.static Method[]
getMethods
(Class<?> clazz, String... methodNames) Get an array ofMethod
's that matches the supplied list of method names.static Method[]
getMethods
(Class<?> clazz, String methodName, Class<?>[] expectedTypes, boolean exactParameterTypeMatch) Get an array ofMethod
's that matches the method name and whose argument types are assignable fromexpectedTypes
.private static Method
getMethodWithMostSpecificParameterTypes
(Method firstMethodCandidate, Method secondMethodCandidate) Find the method whose parameter types most closely matches thetypes
.static <T> Class
<?> getOriginalUnmockedType
(Class<T> type) Gets the unmocked type.private static <T> Constructor
<T> getPotentialConstructorPrimitive
(Class<T> classThatContainsTheConstructorToTest, Class<?>[] argumentTypes) private static <T> Constructor
<T> getPotentialConstructorWrapped
(Class<T> classThatContainsTheConstructorToTest, Class<?>[] argumentTypes) private static <T> Constructor
<T> getPotentialVarArgsConstructor
(Class<T> classThatContainsTheConstructorToTest, Object... arguments) Gets the potential var args constructor.static Class
<?> Gets the type.(package private) static Class
<?> getTypeAsPrimitiveIfWrapped
(Object object) Get the type of an object and convert it to primitive if the type has a primitive counter-part.private static Class<?>[]
Gets the types.static <T> UnproxiedType
getUnproxiedType
(Class<T> type) static Class
<?> getUnproxyType
(Object object) Gets the type.private static sun.misc.Unsafe
private static boolean
hasFieldProperModifier
(Object object, Field field, boolean onlyInstanceFields) Checks for field proper modifier.static <T> T
invokeConstructor
(Class<T> classThatContainsTheConstructorToTest, Class<?>[] parameterTypes, Object[] arguments) Invoke a constructor.static <T> T
invokeConstructor
(Class<T> classThatContainsTheConstructorToTest, Object... arguments) Invoke a constructor.static <T> T
invokeMethod
(Class<?> tested, Object... arguments) Invoke a private or inner class method without the need to specify the method name.static <T> T
invokeMethod
(Class<?> clazz, String methodToExecute, Object... arguments) Invoke a private or inner class method.static <T> T
invokeMethod
(Object object, Class<?> declaringClass, String methodToExecute, Class<?>[] parameterTypes, Object... arguments) Invoke a private method in that is located in a subclass of an instance.static <T> T
invokeMethod
(Object tested, Class<?> declaringClass, String methodToExecute, Object... arguments) Invoke a private or inner class method in that is located in a subclass of the tested instance.static <T> T
invokeMethod
(Object tested, Object... arguments) Invoke a private or inner class method without the need to specify the method name.static <T> T
invokeMethod
(Object tested, String methodToExecute, Class<?>[] argumentTypes, Object... arguments) Invoke a private or inner class method in cases where power mock cannot automatically determine the type of the parameters, for example when mixing primitive types and wrapper types in the same method.static <T> T
invokeMethod
(Object tested, String methodToExecute, Class<?> definedIn, Class<?>[] argumentTypes, Object... arguments) Invoke a private or inner class method in a subclass (defined bydefinedIn
) in cases where power mock cannot automatically determine the type of the parameters, for example when mixing primitive types and wrapper types in the same method.static <T> T
invokeMethod
(Object tested, String methodToExecute, Object... arguments) Invoke a private or inner class method.(package private) static boolean
isAssignableFrom
(Class<?> type, Class<?> from) static boolean
Checks if is class.private static boolean
isPotentialVarArgsMethod
(Method method, Object[] arguments) Checks if is potential var args method.static <T> T
newInstance
(Class<T> classToInstantiate) Create a new instance of a class without invoking its constructor.static <T> T
performMethodInvocation
(Object tested, Method methodToInvoke, Object... arguments) Perform method invocation.private static void
Sets the field.private static void
setFieldUsingUnsafe
(Object base, Class type, long offset, Object newValue, sun.misc.Unsafe unsafe) private static void
setFieldUsingUnsafe
(Field field, Object object, Object newValue) static void
setInternalState
(Object object, Class<?> fieldType, Object value) Set the value of a field using reflection.static void
setInternalState
(Object object, Class<?> fieldType, Object value, Class<?> where) Set the value of a field using reflection at a specific location ( where) in the class hierarchy.static void
setInternalState
(Object object, Object value, Class<?> where) Set the value of a field using reflection at at specific place in the class hierarchy (where).static void
setInternalState
(Object object, Object value, Object... additionalValues) Set the value of a field using reflection.static void
setInternalState
(Object object, String fieldName, Object value) Set the value of a field using reflection.static void
setInternalState
(Object object, String fieldName, Object[] value) Set the value of a field using reflection.static void
setInternalState
(Object object, String fieldName, Object value, Class<?> where) Set the value of a field using reflection.static void
setInternalStateFromContext
(Object object, Class<?> context, Class<?>[] additionalContexts) Set the values of multiple static fields defined in a context using reflection.static void
setInternalStateFromContext
(Object object, Object context, Object[] additionalContexts) Set the values of multiple instance fields defined in a context using reflection.static void
setInternalStateFromContext
(Object object, Object context, FieldMatchingStrategy strategy) private static void
setStaticFieldUsingUnsafe
(Field field, Object newValue) (package private) static void
throwExceptionIfConstructorWasNotFound
(Class<?> type, Constructor<?> potentialConstructor, Object... arguments) Throw exception if constructor was not found.static void
throwExceptionIfFieldWasNotFound
(Class<?> type, String fieldName, Field field) Throw exception if field was not found.static void
throwExceptionIfMethodWasNotFound
(Class<?> type, String methodName, Method methodToMock, Object... arguments) Throw exception if method was not found.(package private) static void
throwExceptionWhenMultipleConstructorMatchesFound
(Constructor<?>[] constructors) Throw exception when multiple constructor matches found.(package private) static void
throwExceptionWhenMultipleMethodMatchesFound
(String helpInfo, Method[] methods) Throw exception when multiple method matches found.private static Class
<?> toBoxedIfPrimitive
(Class<?> type)
-
Field Details
-
proxyFrameworks
The proxy framework. -
allClassMethodsCache
"Strong" map prevent class and method objects from being GCed and unloaded. TODO replace with ClassValue when Powermock drops Java 6 support.
-
-
Constructor Details
-
WhiteboxImpl
public WhiteboxImpl()
-
-
Method Details
-
getMethod
Convenience method to get a method from a class type without having to catch the checked exceptions otherwise required. These exceptions are wrapped as runtime exceptions. The method will first try to look for a declared method in the same class. If the method is not declared in this class it will look for the method in the super class. This will continue throughout the whole class hierarchy. If the method is not found anMethodNotFoundException
is thrown. Since the method name is not specified an- Parameters:
type
- The type of the class where the method is located.parameterTypes
- All parameter types of the method (may benull
).- Returns:
- A .
TooManyMethodsFoundException
is thrown if two or more methods matches the same parameter types in the same class.
-
getMethod
Convenience method to get a method from a class type without having to catch the checked exceptions otherwise required. These exceptions are wrapped as runtime exceptions. The method will first try to look for a declared method in the same class. If the method is not declared in this class it will look for the method in the super class. This will continue throughout the whole class hierarchy. If the method is not found anIllegalArgumentException
is thrown.- Parameters:
type
- The type of the class where the method is located.methodName
- The method names.parameterTypes
- All parameter types of the method (may benull
).- Returns:
- A .
-
getField
Convenience method to get a field from a class type. The method will first try to look for a declared field in the same class. If the method is not declared in this class it will look for the field in the super class. This will continue throughout the whole class hierarchy. If the field is not found anIllegalArgumentException
is thrown.- Parameters:
type
- The type of the class where the method is located.fieldName
- The method names.- Returns:
- A .
-
newInstance
Create a new instance of a class without invoking its constructor. No byte-code manipulation is needed to perform this operation and thus it's not necessary use thePowerMockRunner
orPrepareForTest
annotation to use this functionality.- Type Parameters:
T
- The type of the instance to create.- Parameters:
classToInstantiate
- The type of the instance to create.- Returns:
- A new instance of type T, created without invoking the constructor.
-
getConstructor
Convenience method to get a (declared) constructor from a class type without having to catch the checked exceptions otherwise required. These exceptions are wrapped as runtime exceptions. The constructor is also set to accessible.- Parameters:
type
- The type of the class where the constructor is located.parameterTypes
- All parameter types of the constructor (may benull
).- Returns:
- A .
-
setInternalState
Set the value of a field using reflection. This method will traverse the super class hierarchy until a field with name fieldName is found.- Parameters:
object
- the object whose field to modifyfieldName
- the name of the fieldvalue
- the new value of the field
-
setInternalState
Set the value of a field using reflection. This method will traverse the super class hierarchy until a field with name fieldName is found.- Parameters:
object
- the object to modifyfieldName
- the name of the fieldvalue
- the new value of the field
-
setInternalState
Set the value of a field using reflection. This method will traverse the super class hierarchy until the first field of type fieldType is found. The value will then be assigned to this field.- Parameters:
object
- the object to modifyfieldType
- the type of the fieldvalue
- the new value of the field
-
setInternalState
Set the value of a field using reflection. This method will traverse the super class hierarchy until the first field assignable to the value type is found. The value (or additionaValues if present) will then be assigned to this field.- Parameters:
object
- the object to modifyvalue
- the new value of the fieldadditionalValues
- Additional values to set on the object
-
setInternalState
Set the value of a field using reflection at at specific place in the class hierarchy (where). This first field assignable to object will then be set to value.- Parameters:
object
- the object to modifyvalue
- the new value of the fieldwhere
- the class in the hierarchy where the field is defined
-
setInternalState
public static void setInternalState(Object object, Class<?> fieldType, Object value, Class<?> where) Set the value of a field using reflection at a specific location ( where) in the class hierarchy. The value will then be assigned to this field.- Parameters:
object
- the object to modifyfieldType
- the type of the field the should be set.value
- the new value of the fieldwhere
- which class in the hierarchy defining the field
-
setInternalState
Set the value of a field using reflection. Use this method when you need to specify in which class the field is declared. This is useful if you have two fields in a class hierarchy that has the same name but you like to modify the latter.- Parameters:
object
- the object to modifyfieldName
- the name of the fieldvalue
- the new value of the fieldwhere
- which class the field is defined
-
getInternalState
Get the value of a field using reflection. This method will iterate through the entire class hierarchy and return the value of the first field named fieldName. If you want to get a specific field value at specific place in the class hierarchy please refer to- Type Parameters:
T
- the generic type- Parameters:
object
- the object to modifyfieldName
- the name of the field- Returns:
- the internal state
getInternalState(Object, String, Class)
.
-
findFieldInHierarchy
Find field in hierarchy.- Parameters:
object
- the objectfieldName
- the field name- Returns:
- the field
-
findFieldInHierarchy
Find field in hierarchy.- Parameters:
object
- the objectstrategy
- the strategy- Returns:
- the field
-
findField
Find field.- Parameters:
object
- the objectstrategy
- the strategywhere
- the where- Returns:
- the field
-
findSingleFieldUsingStrategy
private static Field findSingleFieldUsingStrategy(FieldMatcherStrategy strategy, Object object, boolean checkHierarchy, Class<?> startClass) Find single field using strategy.- Parameters:
strategy
- the strategyobject
- the objectcheckHierarchy
- the check hierarchystartClass
- the start class- Returns:
- the field
-
findAllFieldsUsingStrategy
private static Set<Field> findAllFieldsUsingStrategy(FieldMatcherStrategy strategy, Object object, boolean checkHierarchy, boolean onlyInstanceFields, Class<?> startClass) Find all fields using strategy.- Parameters:
strategy
- the strategyobject
- the objectcheckHierarchy
- the check hierarchyonlyInstanceFields
- whether to only allow instance fieldsstartClass
- the start class- Returns:
- the set
-
hasFieldProperModifier
private static boolean hasFieldProperModifier(Object object, Field field, boolean onlyInstanceFields) Checks for field proper modifier.- Parameters:
object
- the objectfield
- the fieldonlyInstanceFields
- whether to only allow instance fields- Returns:
- true, if successful
-
getInternalState
Get the value of a field using reflection. This method will traverse the super class hierarchy until the first field of type fieldType is found. The value of this field will be returned.- Type Parameters:
T
- the generic type- Parameters:
object
- the object to modifyfieldType
- the type of the field- Returns:
- the internal state
-
getInternalState
Get the value of a field using reflection. Use this method when you need to specify in which class the field is declared. The first field matching the fieldType in where will is the field whose value will be returned.- Type Parameters:
T
- the expected type of the field- Parameters:
object
- the object to modifyfieldType
- the type of the fieldwhere
- which class the field is defined- Returns:
- the internal state
-
getInternalState
Get the value of a field using reflection. Use this method when you need to specify in which class the field is declared. This might be useful when you have mocked the instance you are trying to access. Use this method to avoid casting.- Type Parameters:
T
- the expected type of the field- Parameters:
object
- the object to modifyfieldName
- the name of the fieldwhere
- which class the field is defined- Returns:
- the internal state
-
invokeMethod
Invoke a private or inner class method without the need to specify the method name. This is thus a more refactor friendly version of the- Type Parameters:
T
- the generic type- Parameters:
tested
- the testedarguments
- the arguments- Returns:
- the t
- Throws:
Exception
- the exceptioninvokeMethod(Object, String, Object...)
method and is recommend over this method for that reason. This method might be useful to test private methods.
-
invokeMethod
Invoke a private or inner class method without the need to specify the method name. This is thus a more refactor friendly version of the- Type Parameters:
T
- the generic type- Parameters:
tested
- the testedarguments
- the arguments- Returns:
- the t
- Throws:
Exception
- the exceptioninvokeMethod(Object, String, Object...)
method and is recommend over this method for that reason. This method might be useful to test private methods.
-
invokeMethod
public static <T> T invokeMethod(Object tested, String methodToExecute, Object... arguments) throws Exception Invoke a private or inner class method. This might be useful to test private methods.- Type Parameters:
T
- the generic type- Parameters:
tested
- the testedmethodToExecute
- the method to executearguments
- the arguments- Returns:
- the t
- Throws:
Exception
- the exception
-
invokeMethod
public static <T> T invokeMethod(Object tested, String methodToExecute, Class<?>[] argumentTypes, Object... arguments) throws Exception Invoke a private or inner class method in cases where power mock cannot automatically determine the type of the parameters, for example when mixing primitive types and wrapper types in the same method. For most situations useinvokeMethod(Class, String, Object...)
instead.- Type Parameters:
T
- the generic type- Parameters:
tested
- the testedmethodToExecute
- the method to executeargumentTypes
- the argument typesarguments
- the arguments- Returns:
- the t
- Throws:
Exception
- Exception that may occur when invoking this method.
-
invokeMethod
public static <T> T invokeMethod(Object tested, String methodToExecute, Class<?> definedIn, Class<?>[] argumentTypes, Object... arguments) throws Exception Invoke a private or inner class method in a subclass (defined bydefinedIn
) in cases where power mock cannot automatically determine the type of the parameters, for example when mixing primitive types and wrapper types in the same method. For most situations use- Type Parameters:
T
- the generic type- Parameters:
tested
- the testedmethodToExecute
- the method to executedefinedIn
- the defined inargumentTypes
- the argument typesarguments
- the arguments- Returns:
- the t
- Throws:
Exception
- Exception that may occur when invoking this method.invokeMethod(Class, String, Object...)
instead.
-
invokeMethod
public static <T> T invokeMethod(Object tested, Class<?> declaringClass, String methodToExecute, Object... arguments) throws Exception Invoke a private or inner class method in that is located in a subclass of the tested instance. This might be useful to test private methods.- Type Parameters:
T
- the generic type- Parameters:
tested
- the testeddeclaringClass
- the declaring classmethodToExecute
- the method to executearguments
- the arguments- Returns:
- the t
- Throws:
Exception
- Exception that may occur when invoking this method.
-
invokeMethod
public static <T> T invokeMethod(Object object, Class<?> declaringClass, String methodToExecute, Class<?>[] parameterTypes, Object... arguments) throws Exception Invoke a private method in that is located in a subclass of an instance. This might be useful to test overloaded private methods. Use this for overloaded methods only, if possible use- Type Parameters:
T
- the generic type- Parameters:
object
- the objectdeclaringClass
- the declaring classmethodToExecute
- the method to executeparameterTypes
- the parameter typesarguments
- the arguments- Returns:
- the t
- Throws:
Exception
- Exception that may occur when invoking this method.invokeMethod(Object, Object...)
orinvokeMethod(Object, String, Object...)
instead.
-
invokeMethod
public static <T> T invokeMethod(Class<?> clazz, String methodToExecute, Object... arguments) throws Exception Invoke a private or inner class method. This might be useful to test private methods.- Type Parameters:
T
- the generic type- Parameters:
clazz
- the clazzmethodToExecute
- the method to executearguments
- the arguments- Returns:
- the t
- Throws:
Exception
- the exception
-
doInvokeMethod
private static <T> T doInvokeMethod(Object tested, Class<?> declaringClass, String methodToExecute, Object... arguments) throws Exception Do invoke method.- Type Parameters:
T
- the generic type- Parameters:
tested
- the testeddeclaringClass
- the declaring classmethodToExecute
- the method to executearguments
- the arguments- Returns:
- the t
- Throws:
Exception
- the exception
-
findMethodOrThrowException
public static Method findMethodOrThrowException(Object tested, Class<?> declaringClass, String methodToExecute, Object[] arguments) Finds and returns a certain method. If the method couldn't be found this method delegates to- Parameters:
tested
- The instance or class containing the method.declaringClass
- The class where the method is supposed to be declared (may benull
).methodToExecute
- The method name. Ifnull
then method will be looked up based on the argument types only.arguments
- The arguments of the methods.- Returns:
- A single method.
- Throws:
MethodNotFoundException
- if no method was found.TooManyMethodsFoundException
- if too methods matched.IllegalArgumentException
- iftested
is null.
-
getMethodWithMostSpecificParameterTypes
private static Method getMethodWithMostSpecificParameterTypes(Method firstMethodCandidate, Method secondMethodCandidate) Find the method whose parameter types most closely matches thetypes
.- Parameters:
firstMethodCandidate
- The first method candidatesecondMethodCandidate
- The second method candidate- Returns:
- The method that most closely matches the provided types or
null
if no method match.
-
toBoxedIfPrimitive
-
getTypes
Gets the types.- Parameters:
arguments
- the arguments- Returns:
- the types
-
getBestMethodCandidate
public static Method getBestMethodCandidate(Class<?> cls, String methodName, Class<?>[] signature, boolean exactParameterTypeMatch) Gets the best method candidate.- Parameters:
cls
- the clsmethodName
- the method namesignature
- the signatureexactParameterTypeMatch
-true
if theexpectedTypes
must match the parameter types must match exactly,false
if theexpectedTypes
are allowed to be converted into primitive types if they are of a wrapped type and still match.- Returns:
- the best method candidate
-
findDefaultConstructorOrThrowException
public static Constructor<?> findDefaultConstructorOrThrowException(Class<?> type) throws ConstructorNotFoundException Finds and returns the default constructor. If the constructor couldn't be found this method delegates tothrowExceptionWhenMultipleConstructorMatchesFound(java.lang.reflect.Constructor[])
.- Parameters:
type
- The type where the constructor should be located.- Returns:
- The found constructor.
- Throws:
ConstructorNotFoundException
- if too many constructors was found.
-
findConstructorOrThrowException
Finds and returns any constructor. If the constructor couldn't be found this method delegates tothrowExceptionWhenMultipleConstructorMatchesFound(java.lang.reflect.Constructor[])
.- Parameters:
type
- The type where the constructor should be located.- Returns:
- The found constructor.
- Throws:
TooManyConstructorsFoundException
- if too many constructors was found.
-
filterPowerMockConstructor
Filter power mock constructor.- Parameters:
declaredConstructors
- the declared constructors- Returns:
- the constructor[]
-
findUniqueConstructorOrThrowException
public static Constructor<?> findUniqueConstructorOrThrowException(Class<?> type, Object... arguments) Finds and returns a certain constructor. If the constructor couldn't be found this method delegates to- Parameters:
type
- The type where the constructor should be located.arguments
- The arguments passed to the constructor.- Returns:
- The found constructor.
- Throws:
ConstructorNotFoundException
- if no constructor was found.TooManyConstructorsFoundException
- if too constructors matched.IllegalArgumentException
- iftype
is null.
-
convertArgumentTypesToPrimitive
private static Class<?>[] convertArgumentTypesToPrimitive(Class<?>[] paramTypes, Object[] arguments) Convert argument types to primitive.- Parameters:
paramTypes
- the param typesarguments
- the arguments- Returns:
- the class[]
-
throwExceptionIfMethodWasNotFound
public static void throwExceptionIfMethodWasNotFound(Class<?> type, String methodName, Method methodToMock, Object... arguments) Throw exception if method was not found.- Parameters:
type
- the typemethodName
- the method namemethodToMock
- the method to mockarguments
- the arguments
-
throwExceptionIfFieldWasNotFound
Throw exception if field was not found.- Parameters:
type
- the typefieldName
- the field namefield
- the field
-
throwExceptionIfConstructorWasNotFound
static void throwExceptionIfConstructorWasNotFound(Class<?> type, Constructor<?> potentialConstructor, Object... arguments) Throw exception if constructor was not found.- Parameters:
type
- the typepotentialConstructor
- the potential constructorarguments
- the arguments
-
getArgumentTypesAsString
Gets the argument types as string.- Parameters:
arguments
- the arguments- Returns:
- the argument types as string
-
appendArgument
private static void appendArgument(StringBuilder argumentsAsString, int index, String argumentName, Object[] arguments) Append argument.- Parameters:
argumentsAsString
- the arguments as stringindex
- the indexargumentName
- the argument namearguments
- the arguments
-
invokeConstructor
public static <T> T invokeConstructor(Class<T> classThatContainsTheConstructorToTest, Class<?>[] parameterTypes, Object[] arguments) throws Exception Invoke a constructor. Useful for testing classes with a private constructor when PowerMock cannot determine which constructor to invoke. This only happens if you have two constructors with the same number of arguments where one is using primitive data types and the other is using the wrapped counter part. For example:public class MyClass { private MyClass(Integer i) { ... } private MyClass(int i) { ... }
This ought to be a really rare case. So for most situation, use- Type Parameters:
T
- the generic type- Parameters:
classThatContainsTheConstructorToTest
- the class that contains the constructor to testparameterTypes
- the parameter typesarguments
- the arguments- Returns:
- The object created after the constructor has been invoked.
- Throws:
Exception
- If an exception occur when invoking the constructor.invokeConstructor(Class, Object...)
instead.
-
invokeConstructor
public static <T> T invokeConstructor(Class<T> classThatContainsTheConstructorToTest, Object... arguments) throws Exception Invoke a constructor. Useful for testing classes with a private constructor.- Type Parameters:
T
- the generic type- Parameters:
classThatContainsTheConstructorToTest
- the class that contains the constructor to testarguments
- the arguments- Returns:
- The object created after the constructor has been invoked.
- Throws:
Exception
- If an exception occur when invoking the constructor.
-
getBestCandidateConstructor
private static <T> Constructor<T> getBestCandidateConstructor(Class<T> classThatContainsTheConstructorToTest, Class<?>[] argumentTypes, Object[] arguments) -
getPotentialConstructorWrapped
private static <T> Constructor<T> getPotentialConstructorWrapped(Class<T> classThatContainsTheConstructorToTest, Class<?>[] argumentTypes) -
getPotentialConstructorPrimitive
private static <T> Constructor<T> getPotentialConstructorPrimitive(Class<T> classThatContainsTheConstructorToTest, Class<?>[] argumentTypes) -
argumentTypesEqualsPrimitiveTypes
-
getPotentialVarArgsConstructor
private static <T> Constructor<T> getPotentialVarArgsConstructor(Class<T> classThatContainsTheConstructorToTest, Object... arguments) Gets the potential var args constructor.- Type Parameters:
T
- the generic type- Parameters:
classThatContainsTheConstructorToTest
- the class that contains the constructor to testarguments
- the arguments- Returns:
- the potential var args constructor
-
createInstance
private static <T> T createInstance(Constructor<T> constructor, Object... arguments) throws Exception Creates the instance.- Type Parameters:
T
- the generic type- Parameters:
constructor
- the constructorarguments
- the arguments- Returns:
- the t
- Throws:
Exception
- the exception
-
createAndPopulateVarArgsArray
private static Object createAndPopulateVarArgsArray(Class<?> varArgsType, int varArgsStartPosition, Object... arguments) Creates the and populate var args array.- Parameters:
varArgsType
- the var args typevarArgsStartPosition
- the var args start positionarguments
- the arguments- Returns:
- the object
-
getAllConstructors
Get all declared constructors in the class and set accessible totrue
.- Parameters:
clazz
- The class whose constructors to get.- Returns:
- All constructors declared in this class hierarchy.
-
getAllMethods
Get all methods in a class hierarchy! Both declared an non-declared (no duplicates).- Parameters:
clazz
- The class whose methods to get.- Returns:
- All methods declared in this class hierarchy.
-
doGetAllMethods
-
getAllPublicMethods
Get all public methods for a class (no duplicates)! Note that the class-hierarchy will not be traversed.- Parameters:
clazz
- The class whose methods to get.- Returns:
- All public methods declared in class.
-
getAllFields
Get all fields in a class hierarchy! Both declared an non-declared (no duplicates).- Parameters:
clazz
- The class whose fields to get.- Returns:
- All fields declared in this class hierarchy.
-
getFirstParentConstructor
Get the first parent constructor defined in a super class ofklass
.- Parameters:
klass
- The class where the constructor is located.null
).- Returns:
- A .
-
findMethod
Finds and returns a method based on the input parameters. If noparameterTypes
are present the method will return the first method with namemethodNameToMock
. If no method was found,null
will be returned. If nomethodName
is specified the method will be found based on the parameter types. If neither method name nor parameters are specified an- Type Parameters:
T
- the generic type- Parameters:
type
- the typemethodName
- the method nameparameterTypes
- the parameter types- Returns:
- the method
IllegalArgumentException
will be thrown.
-
getOriginalUnmockedType
Gets the unmocked type.- Type Parameters:
T
- the generic type- Parameters:
type
- the type- Returns:
- the unmocked type
-
getUnproxiedType
-
throwExceptionWhenMultipleMethodMatchesFound
Throw exception when multiple method matches found.- Parameters:
helpInfo
- the help infomethods
- the methods
-
throwExceptionWhenMultipleConstructorMatchesFound
Throw exception when multiple constructor matches found.- Parameters:
constructors
- the constructors
-
findMethodOrThrowException
public static Method findMethodOrThrowException(Class<?> type, String methodName, Class<?>... parameterTypes) Find method or throw exception.- Parameters:
type
- the typemethodName
- the method nameparameterTypes
- the parameter types- Returns:
- the method
-
getMethods
Get an array ofMethod
's that matches the supplied list of method names. Both instance and static methods are taken into account.- Parameters:
clazz
- The class that should contain the methods.methodNames
- Names of the methods that will be returned.- Returns:
- An array of Method's.
-
getMethods
public static Method[] getMethods(Class<?> clazz, String methodName, Class<?>[] expectedTypes, boolean exactParameterTypeMatch) Get an array ofMethod
's that matches the method name and whose argument types are assignable fromexpectedTypes
. Both instance and static methods are taken into account.- Parameters:
clazz
- The class that should contain the methods.methodName
- Names of the methods that will be returned.expectedTypes
- The methods must matchexactParameterTypeMatch
-true
if theexpectedTypes
must match the parameter types must match exactly,false
if theexpectedTypes
are allowed to be converted into primitive types if they are of a wrapped type and still match.- Returns:
- An array of Method's.
-
getFields
Get an array ofField
's that matches the supplied list of field names. Both instance and static fields are taken into account.- Parameters:
clazz
- The class that should contain the fields.fieldNames
- Names of the fields that will be returned.- Returns:
- An array of Field's. May be of length 0 but not .
-
performMethodInvocation
public static <T> T performMethodInvocation(Object tested, Method methodToInvoke, Object... arguments) throws Exception Perform method invocation.- Type Parameters:
T
- the generic type- Parameters:
tested
- the testedmethodToInvoke
- the method to invokearguments
- the arguments- Returns:
- the t
- Throws:
Exception
- the exception
-
getAllMethodExcept
Gets the all method except.- Type Parameters:
T
- the generic type- Parameters:
type
- the typemethodNames
- the method names- Returns:
- the all method except
-
getAllMethodsExcept
public static <T> Method[] getAllMethodsExcept(Class<T> type, String methodNameToExclude, Class<?>[] argumentTypes) Gets the all metods except.- Type Parameters:
T
- the generic type- Parameters:
type
- the typemethodNameToExclude
- the method name to excludeargumentTypes
- the argument types- Returns:
- the all metods except
-
areAllMethodsStatic
Are all methods static.- Parameters:
methods
- the methods- Returns:
- true, if successful
-
areAllArgumentsOfSameType
Check if all arguments are of the same type.- Parameters:
arguments
- the arguments- Returns:
- true, if successful
-
checkArgumentTypesMatchParameterTypes
static boolean checkArgumentTypesMatchParameterTypes(boolean isVarArgs, Class<?>[] parameterTypes, Object[] arguments) Check argument types match parameter types.- Parameters:
isVarArgs
- If the last parameter is a var args.parameterTypes
- the parameter typesarguments
- the arguments- Returns:
- if all actual parameter types are assignable from the expected arguments, otherwise.
-
isAssignableFrom
-
getComponentType
-
getType
Gets the type.- Parameters:
object
- the object- Returns:
- The type of the of an object.
-
getUnproxyType
Gets the type.- Parameters:
object
- the object- Returns:
- The type of the of an object.
-
getInnerClassType
public static Class<Object> getInnerClassType(Class<?> declaringClass, String name) throws ClassNotFoundException Get an inner class type.- Parameters:
declaringClass
- The class in which the inner class is declared.name
- The unqualified name (simple name) of the inner class.- Returns:
- The type.
- Throws:
ClassNotFoundException
- the class not found exception
-
getLocalClassType
public static Class<Object> getLocalClassType(Class<?> declaringClass, int occurrence, String name) throws ClassNotFoundException Get the type of a local inner class.- Parameters:
declaringClass
- The class in which the local inner class is declared.occurrence
- The occurrence of the local class. For example if you have two local classes in thedeclaringClass
you must pass in1
if you want to get the type for the first one or2
if you want the second one.name
- The unqualified name (simple name) of the local class.- Returns:
- The type.
- Throws:
ClassNotFoundException
- the class not found exception
-
getAnonymousInnerClassType
public static Class<Object> getAnonymousInnerClassType(Class<?> declaringClass, int occurrence) throws ClassNotFoundException Get the type of an anonymous inner class.- Parameters:
declaringClass
- The class in which the anonymous inner class is declared.occurrence
- The occurrence of the anonymous inner class. For example if you have two anonymous inner classes classes in thedeclaringClass
you must pass in1
if you want to get the type for the first one or2
if you want the second one.- Returns:
- The type.
- Throws:
ClassNotFoundException
- the class not found exception
-
getFieldsAnnotatedWith
public static Set<Field> getFieldsAnnotatedWith(Object object, Class<? extends Annotation> annotation, Class<? extends Annotation>... additionalAnnotations) Get all fields annotated with a particular annotation. This method traverses the class hierarchy when checking for the annotation.- Parameters:
object
- The object to look for annotations. Note that if're you're passing an object only instance fields are checked, passing a class will only check static fields.annotation
- The annotation type to look for.additionalAnnotations
- Optionally more annotations to look for. If any of the annotations are associated with a particular field it will be added to the resultingSet
.- Returns:
- A set of all fields containing the particular annotation.
-
getFieldsAnnotatedWith
public static Set<Field> getFieldsAnnotatedWith(Object object, Class<? extends Annotation>[] annotationTypes) Get all fields annotated with a particular annotation. This method traverses the class hierarchy when checking for the annotation.- Parameters:
object
- The object to look for annotations. Note that if're you're passing an object only instance fields are checked, passing a class will only check static fields.annotationTypes
- The annotation types to look for- Returns:
- A set of all fields containing the particular annotation(s).
- Since:
- 1.3
-
getFieldsOfType
Get all fields assignable from a particular type. This method traverses the class hierarchy when checking for the type.- Parameters:
object
- The object to look for type. Note that if're you're passing an object only instance fields are checked, passing a class will only check static fields.type
- The type to look for.- Returns:
- A set of all fields of the particular type.
-
getAllInstanceFields
Get all instance fields for a particular object. It returns all fields regardless of the field modifier and regardless of where in the class hierarchy a field is located.- Parameters:
object
- The object whose instance fields to get.- Returns:
- All instance fields in the hierarchy. All fields are set to accessible
-
getAllStaticFields
Get all static fields for a particular type.- Parameters:
type
- The class whose static fields to get.- Returns:
- All static fields. All fields are set to accessible.
-
isClass
Checks if is class.- Parameters:
argument
- the argument- Returns:
- true, if is class
-
checkIfParameterTypesAreSame
public static boolean checkIfParameterTypesAreSame(boolean isVarArgs, Class<?>[] expectedParameterTypes, Class<?>[] actualParameterTypes) Check if parameter types are same.- Parameters:
isVarArgs
- Whether or not the method or constructor contains var args.expectedParameterTypes
- the expected parameter typesactualParameterTypes
- the actual parameter types- Returns:
- if all actual parameter types are assignable from the expected parameter types, otherwise.
-
getField
Gets the field.- Parameters:
fieldName
- the field namewhere
- the where- Returns:
- the field
-
findFieldOrThrowException
Find field or throw exception.- Parameters:
fieldType
- the field typewhere
- the where- Returns:
- the field
-
setField
Sets the field.- Parameters:
object
- the objectvalue
- the valuefoundField
- the found field
-
setStaticFieldUsingUnsafe
-
setFieldUsingUnsafe
-
getUnsafe
private static sun.misc.Unsafe getUnsafe() throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException -
setFieldUsingUnsafe
-
concatenateStrings
Concatenate strings.- Parameters:
stringsToConcatenate
- the strings to concatenate- Returns:
- the string
-
isPotentialVarArgsMethod
Checks if is potential var args method.- Parameters:
method
- the methodarguments
- the arguments- Returns:
- true, if is potential var args method
-
doesParameterTypesMatchForVarArgsInvocation
static boolean doesParameterTypesMatchForVarArgsInvocation(boolean isVarArgs, Class<?>[] parameterTypes, Object[] arguments) Does parameter types match for var args invocation.- Parameters:
isVarArgs
- the is var argsparameterTypes
- the parameter typesarguments
- the arguments- Returns:
- true, if successful
-
getTypeAsPrimitiveIfWrapped
Get the type of an object and convert it to primitive if the type has a primitive counter-part. E.g. if object is an instance ofjava.lang.Integer
this method will returnint.class
.- Parameters:
object
- The object whose type to get.- Returns:
- the type as primitive if wrapped
-
setInternalStateFromContext
public static void setInternalStateFromContext(Object object, Object context, Object[] additionalContexts) Set the values of multiple instance fields defined in a context using reflection. The values in the context will be assigned to values on theinstance
. This method will traverse the class hierarchy when searching for the fields. Example usage: Given:public class MyContext { private String myString = "myString"; protected int myInt = 9; } public class MyInstance { private String myInstanceString; private int myInstanceInt; }
thenWhitebox.setInternalStateFromContext(new MyInstance(), new MyContext());
will set the instance variables ofmyInstance
to the values specified inMyContext
.- Parameters:
object
- the objectcontext
- The context where the fields are defined.additionalContexts
- Optionally more additional contexts.
-
setInternalStateFromContext
public static void setInternalStateFromContext(Object object, Object context, FieldMatchingStrategy strategy) -
setInternalStateFromContext
public static void setInternalStateFromContext(Object object, Class<?> context, Class<?>[] additionalContexts) Set the values of multiple static fields defined in a context using reflection. The values in the context will be assigned to values on theclassOrInstance
. This method will traverse the class hierarchy when searching for the fields. Example usage: Given:public class MyContext { private static String myString = "myString"; protected static int myInt = 9; } public class MyInstance { private static String myInstanceString; private static int myInstanceInt; }
thenWhitebox.setInternalStateFromContext(MyInstance.class, MyContext.class);
will set the static variables ofMyInstance
to the values specified inMyContext
.- Parameters:
object
- the objectcontext
- The context where the fields are defined.additionalContexts
- Optionally more additional contexts.
-
copyState
Copy state.- Parameters:
object
- the objectcontext
- the contextstrategy
- The field matching strategy.
-
assertObjectInGetInternalStateIsNotNull
Assert object in get internal state is not null.- Parameters:
object
- the object
-
convertParameterTypesToPrimitive
Convert parameter types to primitive.- Parameters:
parameterTypes
- the parameter types- Returns:
- the class[]
-
copyToMock
public static <T> void copyToMock(T from, T mock) -
copyToRealObject
public static <T> void copyToRealObject(T from, T to) -
copy
-
copyValues
-
copyValue
- Throws:
IllegalAccessException
-