https://kotlinlang.org logo
Docs
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

    Mendess

    12/10/2021, 10:58 AM
    is it possible to use a verify block to test if a property was accessed? Specifically I have something like this
    class Foo {
        val prop get() = 1
    }
    
    val aFoo = Foo()
    val myService = MyService(aFoo)
    myService.method() // should access Foo::prop
    verify {
        aFoo.prop // doesn't work
    }
    m
    m
    • 3
    • 3
  • k

    Kaushalya

    01/25/2022, 3:39 PM
    How is the performance state in Mockk? https://github.com/mockk/mockk/issues/13 Any recent performance improvements?
    m
    t
    • 3
    • 4
  • v

    Vivek Modi

    01/26/2022, 2:00 PM
    Hey I am getting in this my Unit test
    p
    • 2
    • 4
  • v

    Vivek Modi

    01/26/2022, 10:38 PM
    Hey I am testing Live Data value. When I am mocking it giving me null pointer expection.
    internal fun handleDataResponse() {
            dataLiveData.postValue(true)
            currentDeviceTypeLiveData.postValue(true)
    }
    test
    @Test
    fun `handleDataResponse - Handle connection success `() {
        // STUBBING
        // EXECUTION
        viewModel.handleDataResponse()
        // VERIFICATION
        assertEquals(true, viewModel.dataLiveData.value)
        assertEquals(true, viewModel.currentDeviceTypeLiveData.value)
    }
    n
    • 2
    • 2
  • t

    tim

    02/09/2022, 8:27 PM
    I’m getting a NPE when I use a matcher on a
    value class
    , is this a known issue?
    e
    • 2
    • 4
  • a

    Anton Afanasev

    02/15/2022, 4:48 PM
    Hi all. I have a question regarding sequense/order verification. Consider following: Subject:
    class Example (val dependency : Dependency, val anotherDependency: AnotherDependency ){
        fun doWork() {
            dependency.doSomething()
            anotherDependency.doSomethingElse()
        }
    }
    
    
    class Dependency() {
        fun doSomething() {
            println("do something")
        }
    }
    
    class AnotherDependency() {
        fun doSomethingElse() {
            println("do something")
        }
    }
    Test Class:
    class ExampleTest {
        private val mockDependency = mockk<Dependency>(relaxed = true)
        private val mockAnotherDependency = mockk<AnotherDependency>(relaxed = true)
    
        val subject = Example(mockDependency, mockAnotherDependency)
    
        @Test
        fun `when doWork called`() {
            subject.doWork()
    
            verifyOrder {
                mockDependency.doSomething()
            }
        }
    }
    My tests are passing even though I never verified that
    mockAnotherDependency.doSomethingElse()
    invocation. I wonder if there any way to tell mockk to enforce that if any mock object participating in test-case was not verified the test case fails. Without that check I can seamlessly remove:
    anotherDependency.doSomethingElse()
    from my actual Example.doWork() and tests will still pass.
    m
    • 2
    • 3
  • m

    Michael Vandendriessche

    02/24/2022, 2:48 PM
    Hi everyone! I'm having some trouble setting up unit tests for Android in Kotest and MockK. I recently joined a company who already has an android application which did not contain any unit tests. The code is not made with testability in mind so I'm having some trouble. I recently fixed something in a Fragment so I improved the code but I wouldn't call it great. I would like to write tests for it now. Currently I want to test a kotlin function which calls code like this. The other classes are in Java.
    ClassWithManyStaticMethods.getSomething().method(lateInitialisedField)
    I finally figured out how to mock the static class but stumble upon following error
    lateinit property lateInitialisedField has not been initialized
    . So the
    lateInitialisedField
    is a lateinit in the class I want to test. When I call the function I want to test, the
    lateInitialisedField
    is not initialised. How do I initialise it in the test or prevent the error? The value does not matter for my test, I just want to verify if
    method
    has been called. I tried using
    @InjectMocks
    when I create the class under test and created a mockk
    lateInitialisedField
    in my test but either I'm doing something wrong or this is not the solution. If anyone could point me in the right direction that would be greatly appreciated!
    m
    • 2
    • 3
  • s

    Szymon Jeziorski

    02/26/2022, 1:01 PM
    Hello everyone. I'm trying to make use of
    verify
    - verifying method call with the argument being an object equal to another object comparing field by field but ignoring one or more fields. So far the only reasonable solution I came up with was creating a
    matcher
    using AssertJ's
    usingRecursiveComparison()
    and wrapping it to `runCatching`:
    inline fun <reified T : Any> MockKVerificationScope.matcherFor(expected: T, vararg ignoredFields: String) = match<T> {
        runCatching {
            assertThat(it).usingRecursiveComparison().ignoringFields(*ignoredFields).isEqualTo(expected)
        }.isSuccess
    }
    example usage:
    verify {
        userRepository.save(matcherFor(expectedUser, "id"))
    }
    I found the above to be elegant enough from the calling side but was wondering if there would be any more straightforward way to achieve the same with less overhead at the same time. Thanks in advance for any suggestions!
    m
    • 2
    • 2
  • m

    Michael Vandendriessche

    03/02/2022, 3:26 PM
    Hello everyone, What do I return when I don't care about the return value? I can't return unit since the return type is
    SomeClass
    . Do I have to
    return SomeClass()
    or is there something else available like return any or return whatever?
    m
    c
    • 3
    • 9
  • k

    Klitos Kyriacou

    03/03/2022, 5:51 PM
    Hi, in this piece of code, I'm mocking a JDBC
    ResultSet
    , and therefore its
    getLong()
    method returns a JVM platform type (i.e. it could be
    Long
    or
    Long?
    ):
    val id: Long? = <...>
    every { resultSet.getLong("id") } returns id
    Unfortunately, this results in the error message "Type mismatch: inferred type is Long? but Long was expected." Is this a bug, a known limitation, or something I'm doing wrong? I can work around it like this:
    every { resultSet.getLong("id") as Long? } returns id
    but then IntelliJ IDEA warns me that
    as Long?
    is unnecessary.
    s
    • 2
    • 2
  • p

    phldavies

    03/09/2022, 8:23 PM
    Are there any workarounds to https://github.com/mockk/mockk/issues/791? I’m trying to mock a method call that takes a value class as parameter.
    m
    • 2
    • 2
  • j

    jmfayard

    03/10/2022, 12:37 PM
    Hello, I have a.
    sealed class Either
    which either a
    Left
    or a
    Right
    But actually no, because in my unit tests, mockk creates a subclass of
    Either
    which is neither Left nor Right and break the contract of my type Is there a way to forbit mockkk to create a subclass of a sealed class?
    e
    e
    • 3
    • 6
  • m

    Matthew Laser

    03/10/2022, 4:48 PM
    hey all - I understand that
    inline
    functions aren’t mockable (and not spyable from what I can tell?) does anyone have strategies for verifying that calls to a `MutableStateFlow`’s
    inline fun <T> MutableStateFlow<T>.update(function: (T) -> T)
    is invoked with the correct argument (or invoked at all)?
    p
    • 2
    • 1
  • p

    Pitel

    03/22/2022, 10:43 AM
    I have an object, how can I spy and verify its private calls?
    m
    • 2
    • 2
  • d

    Davis Mohar

    03/25/2022, 2:56 PM
    Hey folks, I've got an intermittently failing mockk issue that I'm curious if anybody else has ever dealt with. We have a metrics interface with a
    timed()
    function that I'm trying to mock:
    interface Metrics {
        suspend fun <T> timed(name: String, f: suspend () -> T): T
    }
    So you would think you could mock that with:
    val mockMetrics: Metrics = mockk()
    val funSlot = slot<suspend () -> Either<Nothing, Transfer>>()
    coEvery { mockMetrics.timed(any(), capture(funSlot)) } coAnswers { funSlot.captured() }
    mockMetrics.timed("metricName") { foo() }
    That is only sometimes correct, which is the worst kind of correct. Depending on how I run the tests (kotest tests running on gradle), the test containing this mock will pass sometimes. When it fails, we get a
    io.mockk.MockKException: no answer found for: Metrics(#3).timed(mmp.process.transfer.latency, continuation {}, continuation {})
    which implies that
    timed
    takes three arguments. I believe that's expected behavior, based on how suspend functions compile behind the scenes. But that also implies that our installed answer on our mocked
    timed
    call complied differently -- but only sometimes. Has anyone dealt with behavior like this before? My current workaround is just writing a custom little MockMetrics class instead of using mockk for it.
    👋 1
    a
    • 2
    • 6
  • a

    André Martins

    03/31/2022, 4:24 PM
    Hey how can one mock a static method that has overloads? I’m trying to mock and it’s giving me the ambiguity error
    e
    • 2
    • 1
  • a

    André Martins

    03/31/2022, 4:27 PM
    Also do I need to explicitly call
    unmockkStatic
    or
    clearStaticMockk
    after done using the static mock?
    :yes: 2
    e
    • 2
    • 1
  • a

    aherbel

    04/07/2022, 6:45 PM
    hi anyone knows the equivalente of
    on
    on Mockito but in MockK? I need to change the response type of an
    every
    call but I found no operator to do this as with the
    on
    operator in Mockito
    e
    • 2
    • 5
  • m

    mcpiroman

    04/09/2022, 6:39 PM
    I have a function with many overloads:
    fun prepareStatement(sql: String): PreparedStatement
    fun prepareStatement(sql: String, resultSetType: Int): PreparedStatement
    fun prepareStatement(sql: String, resultSetType: Int, resultSetConcurrency: Int): PreparedStatement
    fun prepareStatement(sql: String, resultSetType: Int, resultSetConcurrency: Int, resultSetHoldability: Int): PreparedStatement
    What if I want to mock all of them in the same way, whereas I only care about the `sql`parameter? Currently I repeat
    every  {
    block for each overload. Is there more preferred way, e.g. matching functions by name?
    m
    • 2
    • 3
  • j

    Jérémy CROS

    04/13/2022, 3:42 PM
    Hi guys 🙂 Is there anyway to make the second mock declaration work?
    class DummyUseCase {
    
        operator fun invoke(): String = TODO()
    }
    
    @Test
    fun test() {
        val dummyUseCase1: DummyUseCase = mockk()
        every { dummyUseCase1.invoke() } returns ""
        val dummyUseCase2: DummyUseCase = mockk {
            every { this.invoke() } returns ""
        }
    }
    In the second case, I have a compilation error: “Not enough information to infer type variable T” (I’m fine with the first declaration but we’ve been trying this
    operator invoke
    thing for our use cases that was showcased in one of the recent MAD Skills video and we use sometimes the second mock declaration) Thanks! 🙂
    s
    e
    • 3
    • 10
  • c

    Chico

    04/13/2022, 7:15 PM
    Hello guys, I have this exemple the DictKey.get will call and external api, then I’m trying to mock
    DictKey.get call, but I'm having this problem Type mismatch: inferred type is DictKey but MockKMatcherScope.DynamicCall was expected
    class A {
       fun callExternalApi(key: String) {
          return DictKey.get(key) 
       }
    }
    But DictKey.get return an instance Of DictKey(….) I would like to stub it What I’m doing..
    val key = "my-key"
    val mockDt = mockk<DictKey>()
    every { mockDt.get(key) } returns what I have to put here?
    val retruanCallExternalApi = A().callExternalApi(key)
    m
    p
    • 3
    • 6
  • m

    Michael de Kaste

    04/14/2022, 2:57 PM
    Hello, how do I effectively mockk a value class?
    e
    • 2
    • 6
  • c

    Chico

    04/14/2022, 4:24 PM
    Hello, I have this function
    fun <T> dummy(arg: Int, argTwo: T) {
      //do something with argTwo
    }
    I tried to mock with
    mockkStatic(::dummy)
    but it said not enough information to infer T, so does anyone knows how can I solve it?
    p
    • 2
    • 2
  • p

    Peter Farlow

    04/19/2022, 6:46 PM
    EDIT: I solved this I’m writing a test for a class handling a 3rd party analytics library. The class under test needs to handler an
    Analytics
    object, but unfortunately
    mockk<Analytics>()
    cannot create a mock because of a static android Handler in that class:
    public class Analytics { // this is 3rd party code I can't change
    
      static final Handler HANDLER =
          new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
              throw new AssertionError("Unknown handler message received: " + msg.what);
            }
          };
    // rest of class here
    }
    I tried using both
    mockk<Analytics>()
    and adding
    mockkConstructor(Handler::class)
    but that didn’t work. Any suggestions?
    m
    • 2
    • 8
  • a

    André Martins

    04/20/2022, 4:41 PM
    Hey I’m getting an error when trying to mock a KMongo
    CoroutineCollection
    with the following code
    data class User(val id: Int, val name: String)
    
    class Service(private val myDatabase: CoroutineDatabase) {
        private val userCollection: CoroutineCollection<User> = myDatabase.getCollection("users")
        suspend fun getById(id: Int): User? = userCollection.findOneById(id)
        // ...
        suspend fun insertUser(user: User): InsertOneResult = userCollection.insertOne(user)
    }
    
    @Test
    fun myTest(): Unit = runBlocking {
        // Arrange
        val database = mockk<CoroutineDatabase>()
        val userCol = mockk<CoroutineCollection<User>>()
    
        every {
            database.getCollection<User>("users")
        } returns userCol
    
    
        val service = Service(database)
        val expectedUser = User(30, "Joe")
    
        coEvery {
            userCol.findOneById(30)
        } returns expectedUser
    
    
        // Act
        val actualUser = service.getById(30)
    
        // Assert
        assertEquals(expectedUser, actualUser)
    }
    The error is
    class org.litote.kmongo.coroutine.CoroutineCollection cannot be cast to class com.mongodb.reactivestreams.client.MongoCollection (org.litote.kmongo.coroutine.CoroutineCollection and com.mongodb.reactivestreams.client.MongoCollection are in unnamed module of loader 'app')
    I suspect this is due to functions like
    CoroutineDatabase::getCollection<T>(String)
    being inline
    m
    • 2
    • 2
  • p

    pepe

    04/21/2022, 8:34 AM
    hey! this question remained unanswered a couple of years ago and now I find myself wondering the same. Let’s see if this time I succeed 🙂 Can someone help me here?
    c
    • 2
    • 2
  • a

    André Martins

    04/21/2022, 12:12 PM
    Hey I’m having issues mocking an extension property, how can one do it? Suppose I have
    class MyService { … }
    and an extension property like
    val MyService.myProp: String
        get() = "value"
    when doing
    mockk<MyService> {
        every { myProp } returns "otherValue"
    }
    it throws a
    MockkException
    msg:
    Missing mocked calls inside every { ... } block: make sure the object inside the block is a mock
    • 1
    • 5
  • a

    André Martins

    04/26/2022, 10:52 AM
    Hello, I have a mocked object and trying to setup
    coEvery
    to mock a specific function although somehow the
    coEvery
    call is hanging when I run the test. What can cause this hanging?
    m
    • 2
    • 15
  • k

    Klitos Kyriacou

    04/29/2022, 12:16 PM
    Hello, the code in the thread gives a warning. Is this intended behaviour or am I abusing Mockk?
    e
    • 2
    • 2
  • m

    Michael de Kaste

    05/13/2022, 9:10 AM
    Can someone help me with the problem I keep facing with value classes? I have a simple class that holds multiple fields, but one of the is the "Duration" value class of kotlin. when I try to mockk it, (v1.12.2) I keep getting classcastexceptions from Long to Duration
    every { someClass.duration } returns 30.minutes
    I can't run this
    e
    • 2
    • 3
Powered by Linen
Title
m

Michael de Kaste

05/13/2022, 9:10 AM
Can someone help me with the problem I keep facing with value classes? I have a simple class that holds multiple fields, but one of the is the "Duration" value class of kotlin. when I try to mockk it, (v1.12.2) I keep getting classcastexceptions from Long to Duration
every { someClass.duration } returns 30.minutes
I can't run this
e

ephemient

05/13/2022, 11:08 AM
https://github.com/mockk/mockk/issues/813 currently not possible
m

Michael de Kaste

05/13/2022, 11:31 AM
yeah I saw this as well. It is what it is, but now I literally have no idea how to properly test this 🤔
e

ephemient

05/13/2022, 1:29 PM
does
every { someClass.duration as Any? }.returns(30.minutes as Any?)
work? (just a thought, there's a good chance that doesn't help) otherwise you'll just have to avoid mocking by using the real object or a writing a fake
View count: 17