18

We had a few tests in Java and Mockito, which we are progressively converting into Kotlin and Mockk. There's a problem, though. This simple line:

verify(mockedInteractor).setIndex(1);

When we move it to mockk, we get this:

verify { mockedInteractor.index = 1 }

This of course passes the tests, as it's not actually checking that index was set to 1. It's simply setting the mock's variable to 1. This below has the same effect.

verify { mockedInteractor.setIndex(1) }

Is there a way to verify setters?

Sergi Juanola
  • 6,531
  • 8
  • 56
  • 93

5 Answers5

20

You could try capture:

val fooSlot = slot<String>()
val mockBar = mockk<Bar>()
every { mockBar.foo = capture(fooSlot) } answers { }
assertEquals(fooSlot.captured, "expected")
Cristan
  • 12,083
  • 7
  • 65
  • 69
xilef
  • 2,199
  • 22
  • 16
  • 2
    Wow, thanks! You can also use 'just runs' in place of empty answers: `every { mockBar.foo = capture(fooSlot) } just runs` – Bruno Pereira Jun 11 '21 at 00:06
  • Here's the Mockk documentation on verifying functions which return Unit, including @BrunoPereira's comment about using `just Runs`. https://mockk.io/#returning-unit – M. Palsich Nov 24 '21 at 17:00
8

Yes you can:

verify { mockedInteractor setProperty "index" value 1 }

There are more examples in here https://mockk.io/#private-functions-mocking--dynamic-calls

Eric Lee
  • 81
  • 1
  • 1
7

Compact solution without hardcoded string:

verify { mockedInteractor setProperty MockedInteractor::index.name value 1 }

where MockedInteractor is mockedInteractor class

Hammer
  • 968
  • 1
  • 8
  • 6
4

I'm wondering if this was asked about an earlier version of Mockk, afterall, it is and old question.

verify { mockedInteractor.index = 1 }

does exactly what it says - it verifies that mockedInteractor.index was set to 1. If you don't believe me, try it. Try setting mockedInteractor.index to something other than 1 in the product code and watch this test fail.

Maybe this was a Mockk bug that has since been fixed.

Myles Bennett
  • 533
  • 4
  • 12
  • Nice, confirmed this works as expected. Did a "red light / green light" test, making sure it fails if the value is wrong. This should be the accepted answer now – Vin Norman Oct 06 '22 at 12:58
1

You can now relax this requirement for unit functions when defining your mock.

val foo = mockk<Foo>(relaxUnitFun = true)

Enabling this setting on your mock means you will not need to use justRun or any variation of that code (as per the Mockk documentation) when verifying unit functions are invoked.

M. Palsich
  • 1,748
  • 13
  • 18