https://kotlinlang.org logo
Join the conversationJoin Slack
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by Linen
mockk
  • m

    marios proto

    10/11/2022, 12:41 PM
    Hi, is there a change from version 1.12.3 onwards regarding the
    mockStatic
    ? The same tests without any code change work with 1.12.3 but not with latest versions.
  • p

    phldavies

    10/25/2022, 7:43 PM
    It seems like
    registerInstanceFactory
    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.
  • k

    KotlinLeaner

    11/07/2022, 9:40 AM
    Hey guys, Can anyone guide me what is the difference between
    spyk
    and
    mockk
    ?
    c
    e
    • 3
    • 4
  • n

    Nick

    11/09/2022, 12:07 AM
    HistoryView
    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
                }
            )
        }
  • t

    thanksforallthefish

    11/09/2022, 12:28 PM
    hello, is there any plan on releasing a new version soon? I see some fixes since 1.13.2
  • m

    Mattia Tommasone

    11/09/2022, 2:00 PM
    i may be publishing a new release later this week or early next week if my day job leaves me enough time 😅
    t
    a
    • 3
    • 4
  • d

    dmcg

    11/11/2022, 9:37 AM
    Hello! https://stackoverflow.com/questions/74400503/how-do-i-mock-a-kotlin-function-type-with-mockk
    e
    • 2
    • 20
  • s

    SomeCat

    11/15/2022, 2:00 PM
    Hello folks. Is anybody here using Mockk with the Eclipse Open J9 JVM?
    t
    • 2
    • 6
  • k

    Klitos Kyriacou

    11/20/2022, 6:58 PM
    Hi, supposing I have a
    mockInstance
    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?
    e
    • 2
    • 1
  • k

    KotlinLeaner

    11/25/2022, 1:21 PM
    Hi, I am testing my function. Inside on function paramter I am passing the
    lamda
    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()
        }
    }
    • 1
    • 2
  • d

    Davide Giuseppe Farella

    11/29/2022, 2:29 PM
    Hey guys, I have a question! Given this
    sealed 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 11
    s
    k
    • 3
    • 4
  • m

    Mattia Tommasone

    11/29/2022, 5:25 PM
    v1.13.3 is out! lots of updates, and, above all, lots of new contributors! Thanks a lot to everyone involved! https://github.com/mockk/mockk/releases/tag/1.13.3
    j
    • 2
    • 1
  • h

    He

    12/03/2022, 12:22 AM
    Hi I want to mock my method
    fun 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 finishes
    m
    • 2
    • 1
  • d

    David Kubecka

    12/07/2022, 6:39 PM
    Hi, quick question: Is mockk supposed to work alongside context receivers? If yes I will write a more detailed issue.
    a
    m
    • 3
    • 3
  • a

    Adam S

    12/08/2022, 9:26 AM
    it’s a little bit awkward that there’s
    every {}
    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’
  • d

    David Kubecka

    12/08/2022, 11:12 AM
    How to mock a method with context receiver? Here's my setup:
    interface 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?
    a
    • 2
    • 3
  • g

    gammax

    12/23/2022, 2:06 PM
    Sharing this with you all folks 🙂 https://kotlinlang.slack.com/archives/C0BJ0GTE2/p1671804380222309
  • m

    Mattia Tommasone

    12/23/2022, 2:21 PM
    Thanks!
  • a

    Adam Pelsoczi

    01/09/2023, 11:14 AM
    If anyone has experience with turbine and mutable state flow. Why would this work:
    val 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)
        }
    }
    a
    e
    • 3
    • 3
  • n

    Nick

    01/13/2023, 12:44 AM
    I don't see
    coAssert
    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?
    e
    • 2
    • 2
  • a

    Ashwini Abhishek

    01/14/2023, 4:48 AM
    Hi, I have been stuck with a problem since past few days, it's regarding coverify incase of a generic class. Have anyone faced this problem https://stackoverflow.com/questions/75089378/why-is-mockk-failing-and-calling-real-method-when-doing-coverifyexactly-0 Please help .
  • a

    Alexandre A Barbosa

    01/16/2023, 8:30 PM
    Hi team. please: is it possible to disable Kafka during my unit tests? I’ve created a class with a method using
    @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?
    e
    • 2
    • 1
  • j

    Jorge Domínguez

    01/27/2023, 5:49 PM
    hello everyone, in my current project we have several instrumentation tests in different packages, when we run the tests in a single package everything works as expected, but if we run several tests in several packages by running from the parent package we get weird
    UninitializedPropertyAccessException
    , 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?
    a
    j
    • 3
    • 16
  • m

    Mattia Tommasone

    01/27/2023, 10:20 PM
    V1.13.4 is out, thanks a lot to @Adam S as always and to a lot of new contributors! Several bugfixes included in the release, check it out! https://github.com/mockk/mockk/releases/tag/v1.13.4
    k
    a
    • 3
    • 4
  • d

    David Kubecka

    02/01/2023, 11:50 AM
    How to mock a method with lambda argument, e.g.
    AsyncTaskExecutor#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.
    • 1
    • 2
  • j

    Jakub Gwóźdź

    02/06/2023, 12:18 PM
    Hi folks. A question about best practice for verifying call arguments in mockk (we’re using strikt here, but the question is general). Imagine such setup:
    interface 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
        }
    ?
    m
    • 2
    • 1
  • r

    Rohan Maity

    02/19/2023, 6:40 PM
    I am having issues in verify block Verify block misses the functions declared inside a function
    fun 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 block
    j
    • 2
    • 2
  • k

    KotlinLeaner

    02/21/2023, 3:28 PM
    Hi guys, I am new in Flow with unit testing. I want to test this function
    internal 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.
    • 1
    • 2
  • r

    Ryunos

    02/22/2023, 2:53 PM
    Hi, is there a way to check which every {} is used when a mock function is called? I’m using IntelliJ and my mocks are behaving strangely, I’m looking for a way to debug
    l
    • 2
    • 2
  • m

    Matteo Mirk

    03/06/2023, 10:30 AM
    Is there a way to configure Mockk at a global level? Say, for example, I'd like all mocks to be relaxed by default.
    m
    t
    j
    • 4
    • 9
Powered by Linen
Title
m

Matteo Mirk

03/06/2023, 10:30 AM
Is there a way to configure Mockk at a global level? Say, for example, I'd like all mocks to be relaxed by default.
m

Mattia Tommasone

03/06/2023, 10:33 AM
yep ci sta 🙂 give me a sec to dig it up
https://mockk.io/#settings-file
relaxed=true
is what you’re looking for
BUT
keep in mind that there is a philosophical argument that mocks should generally be strict and you should just relax them when you really need to
m

Matteo Mirk

03/06/2023, 10:36 AM
Yeah, thanks I know. "relaxed" was just an example, because I couldn't find global settings in the docs... thanks Mattia!
m

Mattia Tommasone

03/06/2023, 10:37 AM
i personally don’t have a very strong opinion about strict vs relaxed mocks, but i know people who do 😄
t

thanksforallthefish

03/06/2023, 1:06 PM
I know people who have strong opinions about mocking interfaces only, and people who have strong opinion against mocking in general. you just can’t please everybody 😄 (sorry, I know it is not contributing to the discussion, feel free to ignore me)
j

Jacob

03/06/2023, 1:09 PM
I like to relax. I feel like mockito docs used to encourage relaxed style, and then pivoted.
View count: 1