'Mock Java interface anonymous implementation in Kotlin with Mockk

I have simple Java interface with one method, which is implemented as anonymous class in Kotlin code using the lambda syntax. I'm trying to mock the interface construction so that the method of the mock would return something else than the original. I'm using MockK for mocking, tried as constructor mock, static mock, object mock and normal class mock, but no luck, still returning the original. Any ideas?

The interface (Java):

public interface TheInterface {
    String getString();
}

The anonymous class implementation and usage (Kotlin):

class SimpleClass {
    fun getStringFromInterface(): String {
        val theInterfaceImpl = TheInterface { "some value" }
        return theInterfaceImpl.getString()
    }
}

Constructor mock attempt (Kotlin):

@Test
fun theTest() {
    mockkConstructor(TheInterface::class)
    every { anyConstructed<TheInterface>().getString() }.returns("MOCK")    
    val simpleClass = SimpleClass()

    // Fails, because "Expected: MOCK; Actual: some value"
    assertEquals("MOCK", simpleClass.getStringFromInterface())
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source