Interface Mocking

import org.junit.Test import kotlin.coroutines.* import kotlinx.coroutines.* import kotlin.test.* import java.util.Date import org.junit.Before import java.lang.Math.pow import java.lang.Math.sqrt import java.util.* import kotlin.test.assertEquals class InterfaceMockingTest { interface Example { fun getInt(): Int } @Test fun `Basic recording test`() { val a = mock<Example>() setReturnValue({ a.getInt() }, 2) assertEquals(2, a.getInt()) var i = 1 val b = mock<Example>() setBody({ b.getInt() }, { i++ }) assertEquals(1, b.getInt()) assertEquals(2, b.getInt()) assertEquals(3, b.getInt()) } } // Your code starts here //sampleStart // implement mock function here //sampleEnd
Save Restore Add own tests Switch to main Feedback

Implement simple interface mocking to make this work:

interface Example {
    fun getInt(): Int
}
val a = mock<Example>()
setReturnValue({ a.getInt() }, 2)
assertEquals(2, a.getInt())

var i = 1
val b = mock<Example>()
setBody({ b.getInt() }, { i++ })
assertEquals(1, b.getInt())
assertEquals(2, b.getInt())
assertEquals(3, b.getInt())

If you are more ambitious, you can push it forward and also allow some arguments. We can preassume that they are passed to the function as a list of Any:

interface Example {
    fun a(i: Int, str: String): Int
}
var i = 1
val = mock<Example>()
setBody({ b.a(any(), any()) }, { (a, str) -> print("$a, $str") })
setBody({ b.a(1, any()) }, { print("This is one!") })
b.a(10, "AAA") // Prints: 10, AAA
b.a(5, "AAA") // Prints: 5, AAA
b.a(1, "AAA") // Prints: This is one!

Test on different interfaces with single and multiple methods. What should happen when a body is set twice to the same method?

Suggestions on how you can solve this problem here.


Previous