Let’s get back to our main topic. So we want to inject
notify and we can achieve that by making
notify a higher-order function so that we can pass
Message.creator in as an argument.
In order to do that, first step, we need get the type right.
Let’s figure out the type of this particular function. Here is the implementation of the original
creator in the SDK:
So it has a type
(PhoneNumber, String, String) -> MessageCreator
which means parameter types on the left side of the arrow “
->” and return type on the right side.
Now let’s define our
typealias to refer to this function type and name it for readability.
But now, we’ve just changed our interface, which is not really nice since normally we don’t need to pass
notify except in test.
In Kotlin, we can avoid that by providing default argument.
So now, our existing interface stays the same and we have our way in!
So we define a
creator that returns a mocked
MessageCreator that stub
create method to return
Message we want.
You might ask, at line 22:
- Why don’t we just use
Messageconstructor? => It’s private.
- Why don’t we mock getters? => It’s final.
So we end up using
And I reference to
creator function by using
::creator, it will regard as a value. The other way, we can use lambda and assign it to
val instead of
By using lambda, we can just ignore the arguments using
_ since we are not using it in this context. This is not possible if we define it with
For more info about how all these functions and lambdas work, you can find out in Kotlin documentation.
Now, we might want to verify if the
creator is being called with correct arguments. The problem is mockito’s
verify only supports method call verification. How can we verify
creator that is not associate to any object?
But turns out, function is actually just a class with
invoke method, so instead of creating function on our own, we can mock the function type. That way, mockito can verify the
invoke method of that function if it’s being called by correct arguments. Here is how function being defined in it’s standard library.
Now we know that we can mock our function to verify the call and we can also stub the return value. Let’s do both!
As you can see, we can verify our function call and stubbing the return value of the static method without hacking the language.