13

I'd like to verify the value which was passed in via a lamdba. The func looks like this:

fun save(entity: Any, idSupplier: () -> UUID): JsonEntity {
    return save(JsonEntity(idSupplier(), entity, entity::class.simpleName!!))
}

Now within my test I'd like to verify the value which has been passed in for the idSupplier. I made a mock to return a value for the save(...) which is called in my own save(..., () -> ...) like this

every { jsonStorage.save(any<JsonEntity>()) } answers { value }

Now on verify I have this now

verify(exactly = 1) { jsonStorage.save(event, any()) }

Which is working, but I'd like to know the exact value which has been passed, i.e. if the entity's id was 123, I'd like to verify this.

Thank you in advance

AlexElin
  • 1,044
  • 14
  • 23
tomhier
  • 570
  • 1
  • 5
  • 15
  • See also [How to run lambda function passed to a mockked method?](https://stackoverflow.com/questions/61108797/how-to-run-lambda-function-passed-to-a-mockked-method) – Vadzim Nov 21 '22 at 10:09

1 Answers1

12

You need a Slot for capturing the parameters.

Example

val id = slot<UUID>()
every { save(any<JsonEntity>()) { capture(id)} } answers { value }

// `id.captured` contains the value passed 
// as a parameter in the lambda expression `idSupplier`

assertEquals(UUID.fromString("4195f789-2730-4f99-8b10-e5b9562210c1"), id.captured)
Omar Mainegra
  • 4,006
  • 22
  • 30
  • Thnx for this answer, this helps me forward. What about the verify-part? Does that remain the same, or can I be more specific inside the verify? – tomhier Dec 24 '18 at 13:40
  • @TomdeVroomen, sure, you can use `id.captured` to verify its value – Omar Mainegra Dec 24 '18 at 13:50
  • @TomdeVroomen I updated my answer to show how to use the `Slot` – Omar Mainegra Dec 24 '18 at 13:56
  • 1
    Thanks for the solution, that brought me on the right track. However, the example didn't quite meet my situation because I wanted to capture the lambda itself. Over on Medium there is a [great article](https://medium.com/@marco_cattaneo/kotlin-unit-testing-with-mockk-91d52aea2852) that does exactly that: `val captureCallback = slot<() -> UUID>(); every { save(capture(captureCallback)) } answers { ... }` – J. Buehler Sep 03 '20 at 11:11
  • @J.Buehler I have never used this function before, but it seems to me that for capturing lambda you can use `captureLambda()` function https://mockk.io/ – shoheikawano Jan 06 '21 at 15:21