Ioannis Mavroukakis
09/19/2022, 4:47 PMkotest
and I am happy with it thus far, except for one little thing that I cannot wrap my head around.
class DummySpec : FreeSpec(
{
val mockedBeeper = mockk<Beeper>()
beforeTest {
clearAllMocks()
println("mock cleared")
}
"beeper will beep" - {
"when the stars have aligned" - {
every { mockedBeeper.beep(any()) } returns "mocked beep"
"and the moon is high" {
mockedBeeper.beep(true) shouldBe "mocked beep"
}
}
}
},
)
class Beeper {
fun beep(shouldBeep: Boolean): String = if (shouldBeep) {
"BEEP"
} else "shhhhh"
}
this will clear the mock
three times, once for each line in the test spec. Is there anyway to use beforeTest
but limit it to be executed only for the top test method? Thanks!FreeSpec
of course, it also applies to the BDD-style spec..LeoColman
09/19/2022, 5:12 PMIoannis Mavroukakis
09/19/2022, 5:13 PMbeforeTest
is executed for every test description 😞LeoColman
09/19/2022, 5:14 PMbeforeContainer
or beforeSpec
?Ioannis Mavroukakis
09/19/2022, 5:15 PMbeforeTest
once
• and ignore other nested descriptionsLeoColman
09/19/2022, 5:17 PMIoannis Mavroukakis
09/19/2022, 5:18 PMmockk
is complaining because "and the moon is high"
runs beforeTest
again and splats the mocked object setupbeforeTest
just once , for when the stars have aligned
clearAllMocks()
doesn't make sense here and I need to create them as `val`sthanksforallthefish
09/20/2022, 6:18 AMclearMockks(answer = false)
, but in general I agree that it seems to me there is something wrong with your setupIoannis Mavroukakis
09/20/2022, 8:04 AMbeforeTest
just once, not once for every nesting level.thanksforallthefish
09/20/2022, 8:06 AMIoannis Mavroukakis
09/20/2022, 8:08 AM"beeper will beep"
, "when the stars have aligned"
and "and the moon is high"
, beforeTest
gets invoked every time. If this is by design, fine, but it means that any mockk
setup in-between them, will get resetclearAlllMocks
between tests might be wrong in the first place but when you are translating JUnit based tests to the FreeSpec or BDD styles, it's a weird little gotcha.thanksforallthefish
09/20/2022, 8:50 AMclass DummySpec : FreeSpec(
{
val mockedBeeper = mockk<Beeper>()
"beeper will beep" - {
clearAllMocks()
println("mock cleared")
"when the stars have aligned" - {
every { mockedBeeper.beep(any()) } returns "mocked beep"
"and the moon is high" {
mockedBeeper.beep(true) shouldBe "mocked beep"
}
}
}
},
)
class Beeper {
fun beep(shouldBeep: Boolean): String = if (shouldBeep) {
"BEEP"
} else "shhhhh"
}
also clears only once, but ofc does not scale if you have many top level “tests” in your spec.
maybe you should really look at isolation, there might something there. I never fully understood it and felt it opens up for bad practices (somehow we have many many tests all works with default isolation, but we are also not using “crazy” set ups and prefer duplicating stuff in tests to keep them simple)Ioannis Mavroukakis
09/20/2022, 8:51 AM