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
  • l

    LeoColman

    05/07/2020, 9:51 PM
    I believe
    any<Type>()
    works as well
    p
    • 2
    • 1
  • d

    Diego Almeida de Oliveira

    05/13/2020, 12:10 PM
    I couldn't find anything about extension properties, neither in the documentation, nor issues on Github, nor stackoverflow, etc. I wonder if this is something so clear for everyone that doesn't need explanation and I'm just missing something
    b
    • 2
    • 4
  • t

    Thomas Nordmeyer

    05/19/2020, 10:34 AM
    Hi all, how do I mockk a setter? Gettng complaints in test because the setter is called at init time of a mocked object.
    every {mocked.myProperty } returns "some"
    mockes the getter. How do I do the same for the setter?
    e
    • 2
    • 2
  • r

    rkeazor

    05/21/2020, 4:10 PM
    Anyone try to mock databinding with mockk?
    g
    • 2
    • 1
  • l

    LeoColman

    06/05/2020, 5:52 PM
    I believe you can transform a class in a KClass
    l
    • 2
    • 1
  • p

    Pacane

    06/08/2020, 7:45 PM
    I was trying to use
    answers ManyAnswersAnswer
    with a
    listOf(ThrowingAnswer(myException), ConstantAnswer(myConstant))
    but it doesn't seem to like having 2 types of answers in there
    a
    • 2
    • 1
  • t

    thanksforallthefish

    06/23/2020, 8:35 AM
    this feels a bit weird to me
    "f:can sync" {
      val clock = mockk<Clock>()
      every { clock.instant() } returns YESTERDAY andThen NOW
    }
    
    "f:can delete" {
      val clock = mockk<Clock>()
      every { clock.instant() } returns YESTERDAY andThen NOW andThen NOW
    }
    the first one logs:
    10:33:28.099 [kotest-engine-0 @coroutine#2] DEBUG io.mockk.impl.instantiation.AbstractMockFactory - Creating mockk for Clock name=#1
    10:33:29.228 [kotest-engine-0 @coroutine#2] DEBUG io.mockk.impl.instantiation.AbstractMockFactory - Creating mockk for Instant name=child of #1#2
    the second one
    10:33:29.245 [kotest-engine-0 @coroutine#3] DEBUG io.mockk.impl.instantiation.AbstractMockFactory - Creating mockk for Clock name=#3
    10:33:29.247 [kotest-engine-0 @coroutine#3] DEBUG io.mockk.impl.instantiation.AbstractMockFactory - Creating mockk for Instant name=child of #3#4
    how comes in the first test it takes one second to create a mock?
    l
    • 2
    • 5
  • p

    poohbar

    06/26/2020, 3:48 PM
    is this answer still valid? https://stackoverflow.com/a/49819729
    o
    • 2
    • 16
  • r

    reevn

    07/18/2020, 1:39 PM
    Not sure if this was posted here, but it seems that many people are having problems getting
    MockK
    to run when using
    Kotest
    4+ and running tests with the Kotest IntelliJ plugin: https://github.com/mockk/mockk/issues/459. I'm not sure if this happens for everyone, but if it does then it is blocking all
    Kotest
    users from really working with
    MockK
    in an easy way. It is not clear to me if this is a problem that needs to be fixed on the
    Kotest
    side or
    MockK
    side. Did anybody here experience the problem and have any more information or even workarounds? Please help us out in the issue or here on Slack 🙂.
    l
    s
    t
    • 4
    • 17
  • b

    bbaldino

    07/20/2020, 6:44 PM
    At some point I started seeing debug logs printing from mockk, but can't remember when they started showing up. Is there a way to globally disable them?
    • 1
    • 3
  • h

    huehnerlady

    07/21/2020, 7:47 AM
    Hi, I am pretty new to kotlin and just read a lot about mockk. I used it as well and it does work marvelously. But I am not 100% sure when I should use a slot capturing and when I use just the verify method without it. Can someone help me with giving useCases when I should use these 2 methods?
    ☑️ 1
    g
    • 2
    • 4
  • h

    huehnerlady

    07/23/2020, 7:10 AM
    Testbleeding with @TestFactory: Hi, I am trying to minimize duplications in tests, so I want to Use JUnit5's TestFactory. It works fine for everything, unless it concerns mokk mocks. Example
    import io.mockk.every
    import io.mockk.mockk
    import io.mockk.verify
    import org.junit.jupiter.api.DynamicTest
    import org.junit.jupiter.api.TestFactory
    
    class Test {
    
      private val testService: TestService = mockk(relaxed = true)
    
    
      private val testStrings = listOf("1", "2")
    
      class TestService {
        fun test(string: String): String {
          return string
        }
      }
    
      @TestFactory
      fun tests() = testStrings
          .map { input: String ->
            DynamicTest.dynamicTest("should call service once for '$input'") {
              every {
                testService.test(any())
              } returns "foo"
    
              testService.test(input)
    
              verify(exactly = 1) { testService.test(any()) }
            }
          }
    }
    As you can see in the test, I am calling the mock just once. still, the testoutput is as shown on the screenshot. The second tests always fails. What am I doing wrong here? Can anybody help me? 🙂 I am using mokk 1.10.0, kotlin 1.3.72 and junit 5.6.2
    ☑️ 1
    t
    c
    s
    • 4
    • 14
  • b

    bbaldino

    08/26/2020, 11:14 PM
    I'm running into some trouble trying to verify that a field was not set, am I using the wrong syntax?
    class Foo {
        var field: Int = 0
    }
    
    fun main() {
        val foo = spyk<Foo>()
    
        foo.field = 42
    
        // This works fine
        verify { foo setProperty "field" value 42 }
        // This should fail, but it throws "io.mockk.MockKException: can't find stub io.mockk.MockKMatcherScope$DynamicSetProperty@64a896b0"
        verify { foo setProperty "field" wasNot Called }
    }
    • 1
    • 1
  • j

    Javier

    09/01/2020, 12:04 PM
    Hello I have a problem trying to mock a private method in a sealed class,
    io.mockk.MockKException: can't find function someMethod() for dynamic call
    sealed class SomeSealed {
        private fun someMethod() = ...
    
        data class SomeData() : SomeSealed()
    }
    • 1
    • 1
  • s

    savrov

    09/11/2020, 12:43 PM
    What is the best way to test abstract class? let’s say I have a class A
    abstract class A(param1: Param1, param2: Param2) {
      fun foo() {
        val param1result = param1.get()
        val param2result = param2.get()
        val result = calculateResult(param1result, param2)
      }
      
      abstract fun calculateResult(param1: Param1, param2: Param2): Smth
    }
    Now, I want to test it. But I can not create an instance of A, since its a abstract class. The only way I managed to make it work is to create a real A class and use spyk function:
    class AReal: A {
      override fun calculateResult(...) {
        ...
      }
    }
    
    class Test {
      val aReal = spyk(AReal(...., .....))
    }
    Is there any other better way?
    b
    • 2
    • 4
  • d

    Davide Giuseppe Farella

    09/24/2020, 11:01 AM
    Hello, I have a class like
    class MyClass(val dir: File) {
    
      fun stuff(filesNames: List<String>) {
        ...
        val file = File(dir, fileName)
        if (file.exists())
        ...
      }
    }
    What would be the right way in order to pass the check
    if (file.exists())
    ?
    v
    • 2
    • 3
  • v

    Vladyslav Sitalo

    09/24/2020, 7:35 PM
    Hey there! Is there alternative to Mockito’s
    clearInvocations
    in mockk? (clear invocation log without resetting the stubbing)
    t
    l
    • 3
    • 3
  • m

    Michael Pohl

    09/29/2020, 7:28 AM
    Is there somebody who can tell me how to mock/test a coroutine that takes a while to complete, like a network call? I have something like this in a test:
    coEvery { mockRepo.saveToServer(mockArgument) } returns myResult
    Now this will of course happen immediately. In reality it could take a moment. Now while this call is in flight, I flip a boolean to prevent issuing a second call while the first one is still underway. When it returns, I flip the boolean back. Is there a proper way to unit test this, preferably using
    Mockk
    , of course...?
    j
    c
    • 3
    • 7
  • t

    tim

    10/11/2020, 8:47 PM
    Hello, i'm trying to mock Instant but I can't seem to get it to work. My approach:
    object MockkInstant {
        var value: Instant = Instant.now()
    
        fun mock() {
            mockkStatic(Instant::class)
    
            every {
                Instant.now()
            } answers {
                value.minusMillis(0) // line 22 from stack trace below
            }
        }
    
        fun clear() {
            clearStaticMockk(Instant::class)
        }
    
        fun step(duration: Duration = 1.seconds) {
            value = value.add(duration) // extension function defined elsewhere
        }
    }
    Now in my tests i'm trying to do this:
    "fixes calls to Instant.now()" {
        val a = Instant.now()
        delay(1)
        val b = Instant.now()
        a.shouldBe(b)
    }
    But I'm getting an error from the
    answers
    block:
    Empty list doesn't contain element at index 0.
    java.lang.IndexOutOfBoundsException: Empty list doesn't contain element at index 0.
    	at kotlin.collections.EmptyList.get(Collections.kt:35)
    	at kotlin.collections.EmptyList.get(Collections.kt:23)
    	at io.mockk.MockKAnswerScope.getValueAny(API.kt:3834)
    	at io.mockk.MockKAnswerScope.getValue(API.kt:2188)
    	at io.glimpseprotocol.testing.mockk.MockkInstant$mock$2.invoke(MockkInstant.kt:22)
    	at io.glimpseprotocol.testing.mockk.MockkInstant$mock$2.invoke(MockkInstant.kt:13)
    	at io.mockk.MockKStubScope$answers$1.invoke(API.kt:2092)
    	at io.mockk.MockKStubScope$answers$1.invoke(API.kt:2069)
    	at io.mockk.FunctionAnswer.answer(Answers.kt:19)
    ...
    I've seen other people using returns, but afaik that returns the same Instant object whereas I want to create a new one each time Instant.now() is called. Any suggestions?
    l
    • 2
    • 12
  • s

    Sergio Crespo Toubes

    10/16/2020, 10:39 AM
    Hi, i am trying to throw an error using mockk with flow method but is not working.
    every { manager.startFunction() } throws(error)
    I don´t find any solution, can someone help me please? Thanks.
    g
    • 2
    • 3
  • p

    poohbar

    10/22/2020, 11:19 PM
    I am trying to do something like
    MockkKt.mockk()
    but the
    mockk()
    function does not exist 🤔
    e
    l
    • 3
    • 7
  • t

    thanksforallthefish

    10/23/2020, 9:45 AM
    I might already have asked this, but forgot the answer (or never asked)
    @Test // <- junit5 annotation
    fun publisher() {
        val publisher = mockk<Publisher>(relaxed = true)
        UseCase(publisher).doSomething()
        verify { publisher.publish(any<UseCase.Something>()) }
        verify { publisher.publish(any<String>()) }
    }
    interface Publisher {
        fun publish(any: Any)
        fun publish(event: Event) {
            publish(event as Any)
        }
        class Event(source: Any)
    }
    class UseCase(val publisher: Publisher) {
        fun doSomething() {
            publisher.publish(Something(""))
        }
        data class Something(val something: String)
    }
    the test passes. what am I not seeing?
    j
    • 2
    • 1
  • o

    oleksiyp

    11/13/2020, 8:27 PM
    Yes, in reality I am not devoting my time to mockk. I am persuiting my career. I know that some issues are resolved as PR by volounteers. Happy if community going to grow around mockk, but dont know the way how to achieve this. Again for me it is just time in life to grow professionaly that I cannot miss, so working days/nights and weekends. If some sufficient enough sponsorship also going to happen(through opencollective or other way) I would just hire some devs, but this is not the case now.
    😱 6
    😢 7
    • 1
    • 1
  • s

    savrov

    11/20/2020, 11:40 PM
    Hi, can someone pls explain me the difference between
    mockk()
    and
    any()
    . Why when i have smth like
    coEvery { foo(any()) } returns SomeObject
    it works. But when i replace
    any()
    with
    mockk()
    , its print out:
    exception=io.mockk.MockKException: no answer found for: SomeClass(#9).foo$domain(ParamType(#5), continuation {})))
    b
    t
    • 3
    • 2
  • k

    Kenneth

    11/25/2020, 7:18 AM
    Hi. Is there a way to verify a service inside
    class RequestSupplier : Supplier<Unit>
    (nested class)?
    o
    • 2
    • 1
  • t

    Tiger

    11/30/2020, 7:52 PM
    I've finished writing pages on how to learn MockK coming from Mockito: https://notwoods.github.io/mockk-guidebook/docs/mockito-migrate/ Eventually I'm hoping to have something written for all of MockK's features, but I'm happy to have this section done!
    👍 4
    m
    • 2
    • 2
  • t

    Timur Atakishiev

    12/05/2020, 10:42 AM
    hi guys, I have a function that looks like below
    interface StorageService {
        fun upload(inputStream: InputStream): String
    }
    
    class LocalStorageService: StorageService {
    
        override upload(inputStream: InputStream): String {
            //Some uploading logic
        }
    }
    
    I want to verify that the function was called with the following code
    
    verify {
        storageService.putFile(
            inputStream = withArg { assertEquals("Hello, World!".toByteArray(),it.readBytes())}
        )
    }
    and I got an error, that my inputStreams byteArray is empty, can anyone help me please
    m
    • 2
    • 6
  • c

    christophsturm

    12/05/2020, 12:41 PM
    it seems mockk 1.10.3 does not support jdk 1.8. is that by design?
    io/mockk/proxy/jvm/dispatcher/JvmMockKDispatcher has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0
    m
    • 2
    • 3
  • c

    chao

    01/03/2021, 4:55 PM
    Hello folks, I have recently translated the internal of MockK from Japanese (https://zenn.dev/oboenikui/articles/af44c158f9fa35) to English (https://chao2zhang.medium.com/unraveling-mockks-black-magic-e725c61ed9dd). Please take a look and let me know in case of mistakes and errors.
    👍 1
    o
    l
    • 3
    • 2
  • h

    huehnerlady

    01/13/2021, 4:59 PM
    Hi, Does anyone know how I can use mockk to say “this methos with any parameters”? In spock you have the operator
    *_
    for that (see here) Example
    fun foo(p1: String, p2: Boolean, p3: Int): Boolean
    I want to write something like this in a test:
    every {foo(anyParameters())} returns true
    Currently the only way I know is:
    every {foo(any(), any(), any())} returns true
    Is there a way to be less verbose and just say
    anything
    ? I tried
    allAny()
    as that sounded like what I wanted, but that didn’t help me either, for me it feels like this is the same as
    any()
    ?
    c
    m
    • 3
    • 4
Powered by Linen
Title
h

huehnerlady

01/13/2021, 4:59 PM
Hi, Does anyone know how I can use mockk to say “this methos with any parameters”? In spock you have the operator
*_
for that (see here) Example
fun foo(p1: String, p2: Boolean, p3: Int): Boolean
I want to write something like this in a test:
every {foo(anyParameters())} returns true
Currently the only way I know is:
every {foo(any(), any(), any())} returns true
Is there a way to be less verbose and just say
anything
? I tried
allAny()
as that sounded like what I wanted, but that didn’t help me either, for me it feels like this is the same as
any()
?
c

christophsturm

01/13/2021, 5:07 PM
i think what you want is not possible because kotlin is strictly typed
in the every block you just call the method that you want to mock and for that call to be valid you need to pass 3 parameters
m

Mattia Tommasone

01/13/2021, 8:11 PM
that is correct suppose your
foo
method has two implementations, one taking two parameters and one taking three which one would you be stubbing if you had
anyParameters()
?
h

huehnerlady

01/14/2021, 7:08 AM
@Mattia Tommasone I do not know the implementation of the spock way, but I would guess that both are stubbed then 🤔
View count: 15