Suppose I want to invoke a lambda given to a mock ...
# codereview
d
Suppose I want to invoke a lambda given to a mock (
delayer
) then I would use (this is a question):
Copy code
argumentCaptor<() -> Unit>().apply {
            whenever(delayer.delay(capture())).thenAnswer { 
                firstValue()
            }
        }
? Now suppose I only want to invoke the lambda a defined number of times because the code calles
delay(...)
recursively until the user stops it. How would I do this? I came up with:
Copy code
argumentCaptor<() -> Unit>().apply {
            var invocationCount = 0

            whenever(delayer.delay(capture())).thenAnswer {
                if(invocationCount < times) {
                   ++invocationCount

                   firstValue()
               }
           }
        }
But that does not seem like a clean solution
a
@Daniel What signature does
thenAnswer
have?
d
public abstract OngoingStubbing<T> thenAnswer(org.mockito.stubbing.Answer<?> answer)
from mockito-core
s
not sure if you've seen it but
mockito-kotlin
might have some solution for what you're encountering.
a
@Daniel you could just implement your own
Answer
and use that with a lambda, e.g.:
Copy code
class CountedAnswer<T>(invocationCount: Int, f: () -> T) : Answer<T> {
    private var counter = 0

    override fun answer(InvocationOnMock invocation): T {
        if(counter < invocationCount)
           f()
....
}

//Usage
delayer.delay(capture()).thenAnswer(CountedAnswer { firstValue() })
d
Thank you for your replies! Especially with the CountedAnswer - this is a really nifty idea
!