k314159
k314159

Reputation: 11140

How is mockk's allAny() used

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()?

Upvotes: 5

Views: 2327

Answers (1)

ocos
ocos

Reputation: 2244

Mockk is a fantastic library but some examples in the official documentation are not providing the original mocked class. That leads to ambiguity. 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.

Upvotes: 4

Related Questions