https://kotlinlang.org logo
#kotest
Title
# kotest
a

Alexandre Brown

12/22/2021, 7:41 PM
Hello, basic question here, I usually use Kotest by initializing my mocks with
MockkAnnotations.init(this)
inside the
beforeEach
block and I use
lateinit var
on my mocks. Is this bad or is this the recommended way? I find that using
val
is not always possible as sometimes you have some expectations to setup first.
Copy code
class MyClassTest : StringSpec() {

	private lateinit var myClass: MyInterface

	@RelaxedMockK
	private lateinit var myMock1: MockableThing1

	@RelaxedMockK
	private lateinit var myMock2: MockableThing2

	init {
		beforeEach {
			MockKAnnotations.init(this)

			myClass = MyClass(
				myMock1,
				myMock2
			)
		}
    }
    ...
l

LeoColman

12/22/2021, 8:39 PM
I think you can setup the expectations even with val.
Copy code
class MyClassTest : StringSpec({
    val myMock1 = mockk<MockableThing1>
    val myTarget = MyClass(myMock1)

    "MyTest" {
        every { <http://myMock1.xyz|myMock1.xyz>() } returns "ABC"
        <http://myTarget.xyz|myTarget.xyz>()
    }
})
OR
Copy code
class MyClassTest : StringSpec({
    val myMock1 = mockk<MockableThing1> {
        every { <http://myMock1.xyz|myMock1.xyz>() } returns "ABC"
    }
    val myTarget = MyClass(myMock1)

    "MyTest" {
        <http://myTarget.xyz|myTarget.xyz>()
    }
})
👍 1
This is usually how I write my tests
And you can use
mockk(relaxed = true)
to replacec @RelaxedMockk
a

Alexandre Brown

12/22/2021, 8:42 PM
I'll try it out @LeoColman, thanks!
l

LeoColman

12/22/2021, 8:50 PM
Should also play a bit with IsolationMode if you're using
verify
a

Alexandre Brown

12/22/2021, 8:51 PM
Yes I have a global config for
IsolationMode.InstancePerTest
thank you Just tried your approach, way less boilerplate, I love it!
I'll definitely switch to your approach, thanks again for sharing it @LeoColman
K 2
kotest 2
3 Views