https://kotlinlang.org logo
Title
m

Mario Adam

05/19/2023, 2:10 PM
Hi - and another mockk question. Given the following properties of a class:
val scanObservers = mutableListOf<(Scan) -> Unit>()
var scan: Scan by Delegates.observable(
        Scan(
            "",
            "",
            ""
        )
    ) { _, _, new -> scanObservers.forEach { it(new) } }
How can I add a mocked lambda in my unit test with mockk? Some sort of:
@Test
fun verifyObserver() {
  // Arrange
  val scan = Scan("foo", "bar", "baz")
  val myMockedLambda = whatShouldIPutInHere???
  myObj.scanObservers.add(myMockedLambda)

  // Act
  myObj.scan = scan
  
  // Assert
  verify(exactly = 1) { myMockedLambda(scan) }
}
m

Matteo Mirk

05/19/2023, 3:08 PM
val myMockedLambda = mockk<(Scan) -> Unit>()
if you don't want to repeat the lambda type over, declare a type alias
typealias ScanFn = (Scan) -> Unit
val myMockedLambda = mockk<ScanFn>()
m

Mario Adam

05/19/2023, 3:20 PM
many thanks 🙂