Home > Software design >  How is mockk's allAny() used
How is mockk's allAny() used

Time:06-28

I can't find any documentation on allAny() that I can understand. The official documentation describes it as a "special matcher that uses any() instead of eq() for matchers that are provided as simple arguments". I don't understand what that means.

I have a line that goes

every { mockObject.method(any(), any(), any(), any(), any(), any(), any(), any(), any()) } returns 0

I thought allAny() might be able to replace repeated use of any(), but of course mockObject.method(allAny()) is a syntax error because there are too few parameters.

So what is the use of allAny()?

CodePudding user response:

Mockk is a fantastic library but some examples in the official documentation are not providing the original mocked class. That leads to ambiguity. I am not sure if I understood correctly allAny. The documentation did not help much.

Let's assume that Car class has a method fun accelerate(fromSpeed: Int, toSpeed: Int). In this case, using allAny() paramater will give a syntax error as you mentionned.

However, compiler will not complain if our accelerate method has a default value for toSpeed or fromSpeed.

fun accelerate(fromSpeed: Int, toSpeed: Int = 100) { // ... }

Let's have a test like below.

val car = mockk<Car>(relaxed = true)
car.accelerate(fromSpeed = 10, toSpeed = 20)
car.accelerate(fromSpeed = 30)

// will pass
verify(atLeast = 2) { car.accelerate(allAny()) }

// will not pass
verify(atLeast = 2) { car.accelerate(any()) }

confirmVerified(car)

allAny will pass seamlessly but any will not. any is accepting all values for fromSpeed but not for toSpeed.

Verification failed: call 1 of 1: Car(#1).accelerate(any(), eq(100))). 1 matching calls found, but needs at least 2 calls
Calls:
1) Car(#1).accelerate(10, 20)
2) Car(#1).accelerate(30, 100)

Hope it helps.

  • Related