marios proto
10/11/2022, 12:41 PMmockStatic
? The same tests without any code change work with 1.12.3 but not with latest versions.phldavies
10/25/2022, 7:43 PMregisterInstanceFactory
is no longer working for value
classes. I have a value class that contains some validation in the init{}
block that’s failing when using the new any()
support for value classes.KotlinLeaner
11/07/2022, 9:40 AMspyk
and mockk
?Nick
11/09/2022, 12:07 AMHistoryView
is an AndroidView so I can't mock it. How do I test this code inside the lambda?
@VisibleForTesting
fun attachHistory() {
historyView = HistoryView(get(),
navToPastVisits = ::attachVisitHistory,
handlePastVisitsBackPressed = {
visitHistoryRouter?.let { <------ I want to test the logic here
if(!it.handleBackPress()) {
detachVisitHistory()
}
true
} ?: false
}
)
}
thanksforallthefish
11/09/2022, 12:28 PMMattia Tommasone
11/09/2022, 2:00 PMdmcg
11/11/2022, 9:37 AMSomeCat
11/15/2022, 2:00 PMKlitos Kyriacou
11/20/2022, 6:58 PMmockInstance
that has a member function fun foo(arg: MyClass): Int
, and I want to mock the function foo
only if it takes an arg that is constructed with specific values:
every { mockInstance.foo(MyClass(1, "a", 0)) } returns 42
every { mockInstance.foo(MyClass(1, "a", 1)) } returns 42
every { mockInstance.foo(MyClass(1, "a", 2)) } returns 42
every { mockInstance.foo(MyClass(1, "a", 3)) } returns 42
every { mockInstance.foo(MyClass(1, "a", 4)) } returns 42
...
In fact, I would like to say
every { mockInstance.foo(MyClass(1, "a", any())) } returns 42
but I can't because the argument passed to foo
is a real instance of MyClass
and so I can't pass any()
to it.
Is there a particular matcher I can use?KotlinLeaner
11/25/2022, 1:21 PMlamda
with Arrangement.Vertical
. I tried some piece of code but it giving me error. Can someone help me on this.
fun isBluetoothEnable(
bluetoothOn: () -> Arrangement.Vertical,
bluetoothOff: () -> Arrangement.Vertical
): Arrangement.Vertical {
return if (isBluetoothEnabled) {
bluetoothOn()
} else {
bluetoothOff()
}
}
Davide Giuseppe Farella
11/29/2022, 2:29 PMsealed interface A {
data class B(...): A
data class C(...): A
}
fun something(a: A): Int
every { something(any()) } returns 0
every { something(any<B>() } returns 1
I would expect that something(B(...))
would return 1 ✅ correct
And that something(C(...))
would return 0 ❌ wrong
This is because the Type
in any<Type>()
actually doesn’t “work”.
The correct way to do this is the more verbose one
every { something(any()) } answer {
when (firstArg<A>()) {
is B -> 1
else -> 0 // or error() or whatever
}
}
Is this expected or is it a bug?
Mock 1.13.2 on JVM 11Mattia Tommasone
11/29/2022, 5:25 PMHe
12/03/2022, 12:22 AMfun wait(){
val timeout= TimeHelper.getNow() + timeoutInterval // <- part of class constructor
if(processor.getLag() > 0){
val currentTIme = TimeHelper.getNow()
if(currentTime >= timeout){ System.exit(42) }
Thread.sleep(someTime)
}
}
Is there a way for me to use mockk to either that wait()
has executed for x amount of time with verify(exactly = x) { someProcessor.wait() }
, or Thread.sleep()
has been sleeping for x number of time?
I have something like this in my test class
every { processor.getLag() } returns 1
every { TimeHelper.getNow() } returns 100
So after some number of executions ever{ processor.getLag() } returns 0
to validate that it finishesDavid Kubecka
12/07/2022, 6:39 PMAdam S
12/08/2022, 9:26 AMevery {}
and coEvery {}
. It makes sense, because Kotlin can’t allow suspend funs to be overloaded, so the names have to be different. But it’s still awkward. If I refactor my code to be suspending, I have to rename lots of mocking functions. And if I don’t use coroutines, the coEvery
, coVerify
, coAssert
auto completes aren’t useful, and clutter my auto-complete.
But… what if MockK provided a wrapper function for tests?
@Test
fun myTest() = coMock {
// non suspending function - will use 'every {}'
every { nonSuspendingFunction() } returns 123
// a suspending function - can also use 'every {}'
every { suspendingFunction() } returns 999
}
suspend fun coMock(context: CoMockKContext.() -> Unit)
would provide a coroutine context, and the receiver, CoMockKContext
, would provide suspend fun
versions of the standard MockK DSL.
Pros:
• no more need for all the MockK functions to be duplicated according to suspend/regular functions.
• as a MockK user, if I refactor my code to be suspend/non-suspend then I don’t need to rename the mocking functions
• if I have a non-suspending codebase my auto-complete isn’t cluttered with suspend MockK DSL variants - coroutines become ‘opt-in’David Kubecka
12/08/2022, 11:12 AMinterface AProvider {
context(ContextProvider)
fun getA(a: String) = a
}
class ContextProvider
inline fun <reified T : Any> mockkWithContext(noinline block: context(ContextProvider) T.() -> Unit) =
withContext { mockk<T> { block(this@withContext, this@mockk) } }
fun <T> withContext(block: ContextProvider.() -> T) = ContextProvider().block()
class ContextReceiversTest {
@Test
fun `a test`() {
val aProviderMock: AProvider = mockkWithContext {
every { getA(any()) } answers { firstArg() }
}
println(withContext { aProviderMock.getA("a") })
}
}
As you can see the getA method has ContextProvider
as a receiver. In order to mock it in the test I have to wrap standard mockk
in withContext
which provides the required receiver for getA
. If I run the test, though, it fails on
io.mockk.MockKException: no answer found for: AProvider(#1).getA(com.example.playground.ContextProvider@38b5f25, a)
Apparently mockk expects the receiver as the first argument but obviously I cannot write every { getA(any(), any()) }
. So my question is how can I mock the method in my case?gammax
12/23/2022, 2:06 PMMattia Tommasone
12/23/2022, 2:21 PMAdam Pelsoczi
01/09/2023, 11:14 AMval mutableSharedFlow = MutableSharedFlow<Int>()
mutableSharedFlow.test {
mutableSharedFlow.emit(1)
assertEquals(awaitItem(), 1)
}
and this does not work:
runTest(UnconfinedTestDispatcher()) {
val bleAdapterEnabledFlow = MutableStateFlow(false)
val stateFlow = bleAdapterEnabledFlow.stateIn(this)
stateFlow.test {
bleAdapterEnabledFlow.emit(true)
assertEquals(awaitItem(), true)
}
}
Nick
01/13/2023, 12:44 AMcoAssert
in the codebase at all. I also don't see it in autocomplete, but I do see coEvery
and coVerify
. I'm on 1.13.3
Did it not make it in?Ashwini Abhishek
01/14/2023, 4:48 AMAlexandre A Barbosa
01/16/2023, 8:30 PM@KafkaListener
annotation and when I run the functional tests, I produce a protobuf topic message and the listener works properly to consume that message.
But my unit test need to test this method, and I am using this:
@Autowired
lateinit var ingestionListener: IngestionConsumerListener
to inject my listener and I want to test this method but without the Kafka in memory.
But the test is trying to load the Kafka because I am getting this:
Could not resolve placeholder 'ingestion.config.topic.name' in value "#{'${ingestion.config.topic.name}'}"
that is used in my implementation:
@KafkaListener(
id = "ingestionListener",
topics = ["#{'\${ingestion.config.topic.name}'}"],
groupId = "#{'\${ingestion.consumer.group.id}'}",
concurrency = "#{'\${ingestion.config.consumer.concurrency}'}"
)
fun consumeIngestion(ingestionHttpRequest: ConsumerRecord<String, IngestionHttpRequest.HttpRequest>)
I am trying to use this kind of solution for my first unit test using Kotlin and Kafka:
@EnableAutoConfiguration(exclude = [KafkaAutoConfiguration::class])
but I am still struggling with the error above…
Please any suggestion to fix that? How to test a kafka listener using Java/Kotlin without Kafka in memory?Jorge Domínguez
01/27/2023, 5:49 PMUninitializedPropertyAccessException
, according the the stacktrace the problem traces back to this java.lang.AbstractMethodError: abstract method "boolean kotlin.reflect.KClass.isValue()"
which seems to be related to mockK, has anybody come across this issue before?Mattia Tommasone
01/27/2023, 10:20 PMDavid Kubecka
02/01/2023, 11:50 AMAsyncTaskExecutor#submit
? Currently I'm doing this
val taskExecutor: AsyncTaskExecutor =
mockk {
every { submit(captureLambda()) } answers {
CompletableFuture.completedFuture(lambda<() -> Int>().invoke())
}
}
but getting
Caused by: java.lang.ClassCastException: class java.lang.Object cannot be cast to class kotlin.Function (java.lang.Object is in module java.base of loader 'bootstrap'; kotlin.Function is in unnamed module of loader 'app')
I should probably use hint
but not sure how exactly.Jakub Gwóźdź
02/06/2023, 12:18 PMinterface Dependency {
fun bar(i: Int): Int
}
class Service(val injected: Dependency) {
fun foo(i: Int) = injected.bar(i * 2) / 3
}
private val mock = mockk<Dependency> { every { bar(any()) } returns 42 }
private val service = Service(mock)
Would you rather do `capture`:
@Test
fun testUsingCapture() {
val arg = slot<Int>()
val result = service.foo(100)
verify { mock.bar(capture(arg)) }
expect {
that(arg).captured isEqualTo 200
that(result) isEqualTo 14
}
}
or `withArg`:
@Test
fun testUsingWithArg() {
val result = service.foo(100)
verify {
mock.bar(
withArg {
expectThat(it) isEqualTo 200
}
)
}
expectThat(result) isEqualTo 14
}
?Rohan Maity
02/19/2023, 6:40 PMfun fetch() = callbackFlow {
fun tryEmitData(data) {
// implementation
}
dataProvider.initialize { data, error ->
tryEmitData(data)
}
}
I can see through debugger, tryEmitData
is hit by debugger properly but verify misses the tryEmiData
internal function blockKotlinLeaner
02/21/2023, 3:28 PMinternal suspend fun subscribeAndGetConnectionStateChange(connectGatt: () -> Unit): ConnectionStateChanged {
val triggerEvents = watchGattCallback.triggerBluetoothGattCallbackEvents
return triggerEvents.onSubscription {
connectGatt()
gattConnection = true
}.firstOrNull {
isGattSuccessAndStateConnected(it)
} as ConnectionStateChanged? ?: getGattFailureAndStateDisconnected()
}
this triggerBluetoothGattCallbackEvents
is a type of MutableSharedFlow<GattTriggerEvent>(extraBufferCapacity = 50)
But I am getting error.Ryunos
02/22/2023, 2:53 PMMatteo Mirk
03/06/2023, 10:30 AMMatteo Mirk
03/06/2023, 10:30 AMMattia Tommasone
03/06/2023, 10:33 AMrelaxed=true
is what you’re looking forMatteo Mirk
03/06/2023, 10:36 AMMattia Tommasone
03/06/2023, 10:37 AMthanksforallthefish
03/06/2023, 1:06 PMJacob
03/06/2023, 1:09 PM