public abstract class Expectations extends Object
Expectations
object.
Typically, this is done by instantiating an anonymous subclass containing an instance initialization body, or as we
call it, an expectation block:
// Record one or more expectations on available mocked types/instances. new Expectations() {{ mock1.expectedMethod(anyInt); result = 123; times = 2; mock2.anotherExpectedMethod(1, "test"); result = new String[] {"Abc", "xyz"}; }}; // Exercise tested code, with previously recorded expectations now available for replay. codeUnderTest.doSomething();Rather than creating anonymous subclasses, we can also create named subclasses to be reused in multiple tests. Some examples:
public final class MyReusableExpectations extends Expectations { public MyReusableExpectations(...any parameters...) { // expectations recorded here } } public class ReusableBaseExpectations extends Expectations { protected ReusableBaseExpectations(...) { // expectations here } } @Test public void someTest(@Mocked final SomeType aMock, etc.) { // Record reusable expectations by instantiating a final "...Expectations" class. new MyReusableExpectations(123, "test", etc.); // Record and extend reusable expectations by instantiating a non-final base class. new ReusableBaseExpectations() {{ // additional expectations }}; }During replay, invocations matching a recorded expectation must occur at least once (unless specified otherwise); if, by the end of the test, no matching invocation occurred for a given recorded expectation, the test will fail with a
MissingInvocation
error.
When multiple expectations are recorded, matching invocations are allowed to occur in a different order.
So, the order in which expectations are recorded is not significant.
Besides the special result
field already mentioned, there are several other fields and methods which can be
used inside the expectation block:
a) returns(Object, Object...)
, a convenience method for returning a sequence of values;
b) argument matchers such as anyInt
, anyString
, withNotNull()
, etc., which relax or
constrain the matching of argument values;
c) the times
, minTimes
, and maxTimes
fields, which relax or constrain the expected and/or
allowed number of matching invocations.
By default, the exact instance on which instance method invocations will occur during replay is not verified
to be the same as the instance used when recording the expectation.
That said, instance-specific matching can be obtained by declaring the mocked type as
@Injectable, by using the onInstance(Object)
method, or by declaring multiple mock
fields and/or mock parameters of the same mocked type (so that separate expectations can be recorded for each mock
instance).
Invocations occurring during replay, whether they matched recorded expectations or not, can be explicitly verified
after exercising the code under test.
To that end, we use a set of complementary base classes: Verifications
, VerificationsInOrder
,
FullVerifications
, and FullVerificationsInOrder
.
Similar to expectation blocks, these classes allow us to create verification blocks.
Finally, note that this class has two specialized subclasses: StrictExpectations
and
NonStrictExpectations
.
The first one differs in that 1) each recorded expectation has, by default, a maximum allowed number of invocations
of 1
(one); 2) matching invocations must occur in the same order as recorded; 3) only
matching invocations are allowed, with any occurrence of unmatched invocations causing the test to fail with an
UnexpectedInvocation
error; and 4) use of verification blocks is not supported, since all invocations are
implicitly verified through the strictly recorded sequence of expectations.
The second one is a smaller variation, in which recorded expectations have a minimum expected number of invocations
of 0
(zero), that is, they are allowed to have no matching invocations at all by default.
Most tests can and should only use Expectations
; StrictExpectations
are meant for users who prefer a
mocking style where all expectations are specified before exercising the code under test, or for situations where
the recording of a strict sequence of expectations produces a test that is more succinct or that fails as early as
an unexpected invocation occurs; NonStrictExpectations
are mainly useful for test setup methods
(a @Before
method in JUnit, or @BeforeMethod
in TestNG), where we often end up recording expectations
that get replayed by some tests, but not all.Modifier and Type | Field and Description |
---|---|
protected CharSequence |
$
An string assigned to this field will be used as a prefix for the error message shown for the current expectation
if it's found to be violated.
|
protected Object |
any
Matches any
Object reference received by a parameter of a reference type. |
protected Boolean |
anyBoolean
Matches any
boolean or Boolean value received by a parameter of one of these types. |
protected Byte |
anyByte
Matches any
byte or Byte value received by a parameter of one of these types. |
protected Character |
anyChar
Matches any
char or Character value received by a parameter of one of these types. |
protected Double |
anyDouble
Matches any
double or Double value received by a parameter of one of these types. |
protected Float |
anyFloat
Matches any
float or Float value received by a parameter of one of these types. |
protected Integer |
anyInt
Matches any
int or Integer value received by a parameter of one of these types. |
protected Long |
anyLong
Matches any
long or Long value received by a parameter of one of these types. |
protected Short |
anyShort
Matches any
short or Short value received by a parameter of one of these types. |
protected String |
anyString
Matches any
String value received by a parameter of this type. |
protected int |
maxTimes
A non-negative value assigned to this field will be taken as the maximum number of times that invocations matching
the current expectation should occur during replay.
|
protected int |
minTimes
A non-negative value assigned to this field will be taken as the minimum number of times that invocations matching
the current expectation should occur during replay.
|
protected Object |
result
A value assigned to this field will be taken as the result for the expectation that is being recorded.
|
protected int |
times
A non-negative value assigned to this field will be taken as the exact number of times that invocations matching
the current expectation should occur during replay.
|
Modifier | Constructor and Description |
---|---|
protected |
Expectations()
Registers one or more expectations recorded on available mocked types and/or mocked instances, as written inside
the instance initialization body of an anonymous subclass or the called constructor of a named subclass.
|
protected |
Expectations(Integer numberOfIterations,
Object... classesOrObjectsToBePartiallyMocked)
Same as
Expectations(Object...) , but considering that the invocations inside the block will occur in a
given number of iterations. |
protected |
Expectations(Object... classesOrObjectsToBePartiallyMocked)
Same as
Expectations() , except that one or more classes will be partially mocked according to the
expectations recorded in the expectation block. |
Modifier and Type | Method and Description |
---|---|
protected <T> T |
onInstance(T mockedInstance)
Calling this method causes the expectation recorded/verified on the given mocked instance to match only those
invocations that occur on the same instance, at replay time.
|
protected void |
returns(Object firstValue,
Object... remainingValues)
Specifies that the previously recorded method invocation will return a given sequence of values during replay.
|
protected <T> T |
with(Delegate<? super T> objectWithDelegateMethod)
Applies a custom argument matcher for a parameter in the current expectation.
|
protected <T> T |
withAny(T arg)
Same as
withEqual(Object) , but matching any argument value of the appropriate type. |
protected <T> T |
withArgThat(org.hamcrest.Matcher<? super T> argumentMatcher)
Applies a Hamcrest argument matcher for a parameter in the current expectation.
|
protected <T> T |
withCapture(List<T> valueHolderForMultipleInvocations)
Captures the argument value passed into the associated expectation parameter, for each invocation that matches the
expectation when the tested code is exercised.
|
protected double |
withEqual(double value,
double delta)
Same as
withEqual(Object) , but checking that a numeric invocation argument in the replay phase is
sufficiently close to the given value. |
protected float |
withEqual(float value,
double delta)
Same as
withEqual(Object) , but checking that a numeric invocation argument in the replay phase is
sufficiently close to the given value. |
protected <T> T |
withEqual(T arg)
When passed as argument for an expectation, creates a new matcher that will check if the given value is
equal to the corresponding argument received by a matching invocation. |
protected <T> T |
withInstanceLike(T object)
Same as
withEqual(Object) , but checking that an invocation argument in the replay phase is an instance of
the same class as the given object. |
protected <T> T |
withInstanceOf(Class<T> argClass)
Same as
withEqual(Object) , but checking that an invocation argument in the replay phase is an instance of
the given class. |
protected <T extends CharSequence> |
withMatch(T regex)
Same as
withEqual(Object) , but checking that a textual invocation argument in the replay phase matches
the given regular expression . |
protected <T> T |
withNotEqual(T arg)
Same as
withEqual(Object) , but checking that the invocation argument in the replay phase is different
from the given value. |
protected <T> T |
withNotNull()
Same as
withEqual(Object) , but checking that an invocation argument in the replay phase is not
null . |
protected <T> T |
withNull()
Same as
withEqual(Object) , but checking that an invocation argument in the replay phase is null . |
protected <T extends CharSequence> |
withPrefix(T text)
Same as
withEqual(Object) , but checking that a textual invocation argument in the replay phase starts
with the given text. |
protected <T> T |
withSameInstance(T object)
Same as
withEqual(Object) , but checking that an invocation argument in the replay phase is the exact same
instance as the one in the recorded/verified invocation. |
protected <T extends CharSequence> |
withSubstring(T text)
Same as
withEqual(Object) , but checking that a textual invocation argument in the replay phase contains
the given text as a substring. |
protected <T extends CharSequence> |
withSuffix(T text)
Same as
withEqual(Object) , but checking that a textual invocation argument in the replay phase ends with
the given text. |
protected Object result
Throwable
then it will be thrown when a matching invocation later occurs.
Otherwise, it's assumed to be a return value for a non-void
method, and will be returned
from a matching invocation.
If no result is recorded for a given expectation, then all matching invocations will return the appropriate
default value according to the method return type:
java.lang
types (String
, Object
, etc.): returns null
.java.math
types (BigDecimal
, etc.): returns null
.false
for boolean/Boolean
,
0
for int/Integer
, and so on).
java.util.List
, java.util.Collection
, or java.lang.Iterable
: returns
Collections.EMPTY_LIST
.java.util.Iterator
or java.util.ListIterator
: returns an empty iterator.java.util.Set
: returns Collections.EMPTY_SET
.java.util.SortedSet
: returns an unmodifiable empty sorted set.java.util.Map
: returns Collections.EMPTY_MAP
.java.util.SortedMap
: returns an unmodifiable empty sorted map.java.util.Optional
: returns Optional.empty()
.returns(Object, Object...)
method should be used instead, as it only
applies to return values.
Assigning a value whose type differs from the method return type will cause an IllegalArgumentException
to
be thrown, unless it can be safely converted to the return type.
One such conversion is from an array to a collection or iterator.
Another is from an array of at least two dimensions to a map, with the first dimension providing the keys and the
second the values.
Yet another conversion is from a single value to a container type holding that value.
Additionally, if the value assigned to the field is an array or is of a type assignable to Iterable
or
Iterator
, and the return type is single-valued, then the assigned multi-valued result is taken as a
sequence of consecutive results for the expectation.
Results that depend on some programming logic can be provided through a Delegate object assigned to
the field.
This applies to void
and non-void
methods, as well as to constructors.
Finally, when recording an expectation on a constructor of a mocked class, an arbitrary instance of said
class can be assigned to the field.
In this case, the assigned instance will be used as a "replacement" for all invocations to
instance methods made on other instances, provided they get created sometime later through a
matching constructor invocation.returns(Object, Object...)
,
Tutorialprotected CharSequence $
IllegalStateException
is thrown.
Notice there are only two different ways in which an expectation can be violated: either an unexpected
invocation occurs during replay, or a missing invocation is detected.protected final Object any
Object
reference received by a parameter of a reference type.
This field can only be used as the argument value at the proper parameter position in a method/constructor
invocation, when recording or verifying an expectation; it cannot be used anywhere else.
The use of this field will usually require a cast to the specific parameter type.
However, if there is any other parameter for which an argument matching constraint is specified, passing the
null
reference instead will have the same effect.
When the parameter to be matched is a varargs parameter of element type V
, the use of
any
should be cast to V[]
.
In invocations to non-accessible methods or constructors (for example, with
Deencapsulation.invoke(Object, String, Object...)
), use withAny(T)
instead.protected final Boolean anyBoolean
boolean
or Boolean
value received by a parameter of one of these types.
This field can only be used as the argument value at the proper parameter position in a method/constructor
invocation, when recording or verifying an expectation; it cannot be used anywhere else.protected final Byte anyByte
byte
or Byte
value received by a parameter of one of these types.
This field can only be used as the argument value at the proper parameter position in a method/constructor
invocation, when recording or verifying an expectation; it cannot be used anywhere else.protected final Character anyChar
char
or Character
value received by a parameter of one of these types.
This field can only be used as the argument value at the proper parameter position in a method/constructor
invocation, when recording or verifying an expectation; it cannot be used anywhere else.protected final Double anyDouble
double
or Double
value received by a parameter of one of these types.
This field can only be used as the argument value at the proper parameter position in a method/constructor
invocation, when recording or verifying an expectation; it cannot be used anywhere else.protected final Float anyFloat
float
or Float
value received by a parameter of one of these types.
This field can only be used as the argument value at the proper parameter position in a method/constructor
invocation, when recording or verifying an expectation; it cannot be used anywhere else.protected final Integer anyInt
int
or Integer
value received by a parameter of one of these types.
This field can only be used as the argument value at the proper parameter position in a method/constructor
invocation, when recording or verifying an expectation; it cannot be used anywhere else.protected final Long anyLong
long
or Long
value received by a parameter of one of these types.
This field can only be used as the argument value at the proper parameter position in a method/constructor
invocation, when recording or verifying an expectation; it cannot be used anywhere else.protected final Short anyShort
short
or Short
value received by a parameter of one of these types.
This field can only be used as the argument value at the proper parameter position in a method/constructor
invocation, when recording or verifying an expectation; it cannot be used anywhere else.protected final String anyString
String
value received by a parameter of this type.
This field can only be used as the argument value at the proper parameter position in a method/constructor
invocation, when recording or verifying an expectation; it cannot be used anywhere else.protected int maxTimes
minTimes
and maxTimes
can be specified for the same expectation, as long as minTimes
is assigned first.protected int minTimes
minTimes
and maxTimes
can be specified for the same expectation, as long as minTimes
is assigned first.protected Expectations()
protected Expectations(Integer numberOfIterations, Object... classesOrObjectsToBePartiallyMocked)
Expectations(Object...)
, but considering that the invocations inside the block will occur in a
given number of iterations.
The effect of specifying a number of iterations larger than 1 (one) is equivalent to multiplying by that number
the lower and upper invocation count limits for each invocation inside the expectation block.
It's also valid to have multiple expectation blocks for the same test, each with an arbitrary number of
iterations.numberOfIterations
- the positive number of iterations for the whole set of expectations recorded inside the
block; when not specified, 1 (one) iteration is assumedclassesOrObjectsToBePartiallyMocked
- one or more classes or objects whose classes are to be partially mockedExpectations()
,
Tutorialprotected Expectations(Object... classesOrObjectsToBePartiallyMocked)
Expectations()
, except that one or more classes will be partially mocked according to the
expectations recorded in the expectation block.
The classes to be partially mocked are those directly specified through their Class
objects as well as
those to which any given objects belong.
During replay, any invocations to one of these classes or objects will execute real production code, unless a
matching expectation was recorded.
This mechanism, however, does not apply to native
methods, which are not supported for partial mocking.
For a given Class
object, all constructors and methods can be mocked, from the specified class up to but
not including java.lang.Object
.
For a given object, only methods can be mocked, not constructors; also, during replay, invocations to
instance methods will only match expectations recorded on the given instance (or instances, if more than one was
given).classesOrObjectsToBePartiallyMocked
- one or more classes or objects whose classes are to be partially mockedIllegalArgumentException
- if given a class literal for an interface, an annotation, an array, a
primitive/wrapper type, or a proxy class created for an
interface, or if given a value/instance of such a typeExpectations(Integer, Object...)
,
Tutorialprotected final void returns(Object firstValue, Object... remainingValues)
result
field two or more times in sequence, or
assigning it a single time with an array or iterable containing the same sequence of values.
Certain data conversions will be applied, depending on the return type of the recorded method:
List
value, then the given sequence of values will be
converted into an ArrayList
; this list will then be returned by matching invocations at replay time.SortedSet
or a sub-type, then the given sequence of values will be converted
into a TreeSet
; otherwise, if it is Set
or a sub-type, then a LinkedHashSet
will be
created to hold the values; the set will then be returned by matching invocations at replay time.Iterator
or a sub-type, then the given sequence of values will be converted into
a List
and the iterator created from this list will be returned by matching invocations at replay
time.maxTimes
field, if necessary.
If this method is used for a constructor or void
method, the given return values will be ignored,
but matching invocations will be allowed during replay; they will simply do nothing.firstValue
- the first value to be returned at replay timeremainingValues
- the remaining values to be returned, in the same orderprotected final <T> T onInstance(T mockedInstance)
onInstance(Object)
on each of these different instances of the
same type, instance matching is implied (and automatically applied to all relevant invocations) whenever
two or more mocked instances of the same type are in scope for a given test method. This property of the API makes
the use of onInstance
much less frequent than it might otherwise be.
In most cases, an invocation to the given mocked instance will be made on the value returned by this method (ie,
a chained invocation).
However, in the situation where the tested method calls an instance method defined in a mocked super-class
(possibly an overridden method called through the super
keyword), it will be necessary to match on a
different instance than the one used for recording invocations.
To do so, this method should be given the desired instance to match, while the invocation to be recorded should be
done on the available mocked instance, which must be a different one (otherwise a non-mocked method would get
executed).
This is valid only if the instance to be matched is assignable to the mocked type, and typically occurs when
partially mocking a class hierarchy.protected final <T> T with(Delegate<? super T> objectWithDelegateMethod)
private
delegate method
(plus any number of helper private
methods).
The name of the delegate method doesn't matter, but it must have a single parameter capable of receiving the
relevant argument values.
The return type of the delegate method should be boolean
or void
.
In the first case, a return value of true
will indicate a successful match for the actual invocation
argument at replay time, while a return of false
will fail to match the invocation.
In the case of a void
return type, the actual invocation argument should be validated through a suitable
JUnit/TestNG assertion.objectWithDelegateMethod
- an instance of a class defining a single non-private
delegate methodT
if it's a primitive wrapper type, or null
otherwisewithArgThat(org.hamcrest.Matcher)
,
Tutorialprotected final <T> T withAny(T arg)
withEqual(Object)
, but matching any argument value of the appropriate type.
Consider using instead the "anyXyz" field appropriate to the parameter type:
anyBoolean
, anyByte
, anyChar
, anyDouble
, anyFloat
, anyInt
,
anyLong
, anyShort
, anyString
, or any
for other reference types.
Note: when using Deencapsulation.invoke(Object, String, Object...)
, etc., it's valid to pass
withAny(ParameterType.class)
if an actual instance of the parameter type cannot be created.arg
- an arbitrary value which will match any argument value in the replay phaseprotected final <T> T withArgThat(org.hamcrest.Matcher<? super T> argumentMatcher)
argumentMatcher
- any org.hamcrest.Matcher
objectnull
if there is no such value to be
foundwith(Delegate)
protected final <T> T withCapture(List<T> valueHolderForMultipleInvocations)
valueHolderForMultipleInvocations
- list into which the arguments received by matching invocations will be
addedT
Verifications.withCapture()
,
Verifications.withCapture(Object)
,
Tutorialprotected final double withEqual(double value, double delta)
withEqual(Object)
, but checking that a numeric invocation argument in the replay phase is
sufficiently close to the given value.value
- the center value for range comparisondelta
- the tolerance around the center value, for a range of [value - delta, value + delta]value
protected final float withEqual(float value, double delta)
withEqual(Object)
, but checking that a numeric invocation argument in the replay phase is
sufficiently close to the given value.value
- the center value for range comparisondelta
- the tolerance around the center value, for a range of [value - delta, value + delta]value
protected final <T> T withEqual(T arg)
equal
to the corresponding argument received by a matching invocation.
The matcher is added to the end of the list of argument matchers for the invocation being recorded/verified.
It cannot be reused for a different parameter.
Usually, this particular method should not be used. Instead, simply pass the desired argument value
directly, without any matcher.
Only when specifying values for a varargs method it's useful, and even then only when some other argument
matcher is also used.arg
- the expected argument valueprotected final <T> T withInstanceLike(T object)
withEqual(Object)
, but checking that an invocation argument in the replay phase is an instance of
the same class as the given object.
Equivalent to a withInstanceOf(object.getClass())
call, except that it returns object
instead
of null
.object
- an instance of the desired classprotected final <T> T withInstanceOf(Class<T> argClass)
withEqual(Object)
, but checking that an invocation argument in the replay phase is an instance of
the given class.argClass
- the desired classnull
; if you need a specific return value, use withInstanceLike(Object)
protected final <T extends CharSequence> T withMatch(T regex)
withEqual(Object)
, but checking that a textual invocation argument in the replay phase matches
the given regular expression
.
Note that this can be used for any string comparison, including case insensitive ones (with "(?i)"
in the
regex).regex
- an arbitrary (non-null) regular expression against which textual argument values will be matchedPattern.compile(String, int)
,
Tutorialprotected final <T> T withNotEqual(T arg)
withEqual(Object)
, but checking that the invocation argument in the replay phase is different
from the given value.arg
- an arbitrary value, but different from the ones expected to occur during replayprotected final <T> T withNotNull()
withEqual(Object)
, but checking that an invocation argument in the replay phase is not
null
.null
protected final <T> T withNull()
withEqual(Object)
, but checking that an invocation argument in the replay phase is null
.null
protected final <T extends CharSequence> T withPrefix(T text)
withEqual(Object)
, but checking that a textual invocation argument in the replay phase starts
with the given text.text
- an arbitrary non-null textual valueprotected final <T> T withSameInstance(T object)
withEqual(Object)
, but checking that an invocation argument in the replay phase is the exact same
instance as the one in the recorded/verified invocation.object
- the desired instanceprotected final <T extends CharSequence> T withSubstring(T text)
withEqual(Object)
, but checking that a textual invocation argument in the replay phase contains
the given text as a substring.text
- an arbitrary non-null textual valueprotected final <T extends CharSequence> T withSuffix(T text)
withEqual(Object)
, but checking that a textual invocation argument in the replay phase ends with
the given text.text
- an arbitrary non-null textual value