How to mock a builder using MockK so that the builder functions are commutative?

Viewed 513

I got some code which I want to test using MockK as a mocking library:

fun loadImage(imageLoader: coil.ImageLoader) {
    val request = ImageRequest.Builder(imageView.context)
        .data(url)
        .crossfade(true)
        .build()
    imageLoader.enqueue(request)
}

I am able to mock this using a hierarchical approach:


val request: ImageRequest = mockk()
val imageLoader: coil.ImageLoader = mockk(relaxed = true)
mockkConstructor(ImageRequest.Builder::class)
every { anyConstructed<ImageRequest.Builder>().data(any()) } returns mockk {
    every { crossfade(any<Boolean>()) } returns mockk {
        every { build() } returns request
    }
}

loadImage(imageLoader)

verify { imageLoader.enqueue(request) }

So this is problematic since I also test the order in which the builder functions are called. When I would switch the .data and .crossfade calls the test would break while the implementation still works.

Is there a better way to apprach this?

0 Answers
Related