If you want to change the result of a mocked method depending on its arguments, run additional code whenever a method is called, or just print out “Hello world” when a mock is used, answers
is the tool you’ll want to use.
answers
takes the place of returns
after an every
call. When using returns
, it should be followed by a value to return. When using answers
, it should be followed by a lambda function that is run when the mocked method is called.
A function has “side effects” if it does something other than just returning a value, such as logging or mutating some outside state. answers
lets you model side effects by putting additional statements inside its lambda function.
Answer scope
These values are properties on the MockKAnswerScope class. The scope is passed as a , allowing variables to be called from the implicit this
scope.
Single arugments can be obtained using firstArg()
, secondArg()
, , and lastArg()
. Other arguments can be obtained with arg(n)
, where n
is the index of the argument. For example, arg(3)
would return the fourth argument.
Arguments do not have static type checking. Instead, the type is casted automatically using generic types.
All arguments
The entire list of arguments can be obtained using args
. args
has the type List<Any?>
, so you will need to manually cast values in the list if you want to work with them.
If you only need to know the length of args
, aka the number of arguments, you can use .
TODO call
, invocation
, matcher
, self
, method
, captured
, lambda
, coroutine
, nothing
, fieldValue
, fieldValueAny
, , valueAny
.