如何 mock/match kotlin 方法签名中的 lambda
how to mock/match lambda in kotlin method signature
我在下面的表格上有一些代码:
@Language("SQL")
val someSql = """
SELECT foo
FROM bar
WHERE foo = :foo
"""
return session.select(some, mapOf("foo" to foo)) {
MyObject(
foo = it.string("foo"),
)
}.firstOrNull()
使用以下来自 com.github.andrewoma.kwery.core 的内容。注意方法签名中的 lambda:
fun <R> select(@Language("SQL") sql: String,
parameters: Map<String, Any?> = mapOf(),
options: StatementOptions = defaultOptions,
mapper: (Row) -> R): List<R>
我使用 mockitokotlin2。
当使用 select 查询(包含 "SELECT foo")调用会话 select 方法时,我需要 return MyObject 的实例。
我想我可以像下面这样将模拟传递到 lambda 中(但它不会匹配我试图模拟的方法调用)。下面的代码是一种尝试。但它从不匹配 eq(function2)
:
val function2: (Row) -> Int = mock {
onGeneric { invoke(any()) }.thenReturn(MyObject(foo="test-foo"))
}
val session = mock<Session> {
on { select(sql = any(), parameters = any(), options = any(), mapper = eq(function2))}.thenReturn(listOf(MyObject(foo="test-foo")))
}
function2 在我的例子中并不是真正的映射器,它与我试图模拟的不相等,它永远不会匹配并且永远不会调用模拟。
那么在上面的代码中,我应该在 session, select
的 mock 中而不是 eq(function2) 中放入什么来获取 MyObject 对象 returned?
我认为您只需要在设置会话模拟时指定您的映射器预期 return 的类型 - 在您的情况下看起来是 Function1<Row, MyObject>
val session = mock<Session> {
on { select(sql = anyString(), parameters = anyMap(), options = any(), mapper = any<Function1<Row, MyObject>>())}.thenReturn(listOf(MyObject(foo="test-foo")))
}
我在下面的表格上有一些代码:
@Language("SQL")
val someSql = """
SELECT foo
FROM bar
WHERE foo = :foo
"""
return session.select(some, mapOf("foo" to foo)) {
MyObject(
foo = it.string("foo"),
)
}.firstOrNull()
使用以下来自 com.github.andrewoma.kwery.core 的内容。注意方法签名中的 lambda:
fun <R> select(@Language("SQL") sql: String,
parameters: Map<String, Any?> = mapOf(),
options: StatementOptions = defaultOptions,
mapper: (Row) -> R): List<R>
我使用 mockitokotlin2。
当使用 select 查询(包含 "SELECT foo")调用会话 select 方法时,我需要 return MyObject 的实例。
我想我可以像下面这样将模拟传递到 lambda 中(但它不会匹配我试图模拟的方法调用)。下面的代码是一种尝试。但它从不匹配 eq(function2)
:
val function2: (Row) -> Int = mock {
onGeneric { invoke(any()) }.thenReturn(MyObject(foo="test-foo"))
}
val session = mock<Session> {
on { select(sql = any(), parameters = any(), options = any(), mapper = eq(function2))}.thenReturn(listOf(MyObject(foo="test-foo")))
}
function2 在我的例子中并不是真正的映射器,它与我试图模拟的不相等,它永远不会匹配并且永远不会调用模拟。
那么在上面的代码中,我应该在 session, select
的 mock 中而不是 eq(function2) 中放入什么来获取 MyObject 对象 returned?
我认为您只需要在设置会话模拟时指定您的映射器预期 return 的类型 - 在您的情况下看起来是 Function1<Row, MyObject>
val session = mock<Session> {
on { select(sql = anyString(), parameters = anyMap(), options = any(), mapper = any<Function1<Row, MyObject>>())}.thenReturn(listOf(MyObject(foo="test-foo")))
}