kosi-libs / MocKMP

A mocking processor for Kotlin Multiplatform
https://kosi-libs.org/mockmp
MIT License
183 stars 12 forks source link

Allow open classes to be mocked #37

Closed 89jd closed 1 year ago

89jd commented 2 years ago

Just added a change so that open classes can be mocked for there corresponding open functions.

SalomonBrys commented 1 year ago

Can you give use cases for this? So far, we've intentionally restricted the mocking feature to interfaces.

The reason is that you can only mock abstract / open methods, and therefore only track & verify these (and only these) methods.

Let's consider this class:

open class Foo {
    fun bar() {}
    open fun baz() {}
}

This test will succeed:

@Test
fun testFoo() {
    val foo = MockFoo(mocker)

    mocker.verify {
        foo.bar() // Foo.bar is not open, so it cannot be intercepted by the mocker.
    }
}

In this example, instead of verifying that Foo.bar was called, the method is actually called. The code is correct, but it is perceived wrongly. Even though Foo.bar was never called before the verify block, the test succeeds.

By allowing to mock open classes, we give to the developer the responsibility of tracking which methods are open (and therefore tracked by the mocker), and which are not. This really feels like a recipe for hard-to-debug errors and tests that succeed when they really shouldn't.

Finally, this opens the possibility for lazy developers (which we are all) to mark a method open just to be able to track it in tests, and I am not comfortable encouraging this bad practice.