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

    s1m0nw1

    04/16/2019, 10:10 AM
    Hey, is there a known issue with matching inline class parameters of functions?
    o
    l
    • 3
    • 4
  • m

    mben

    04/17/2019, 2:45 PM
    Hello i'm using implementation 'io.mockk:mockk-common:1.9.3' inside my commonTest.dependencies but have Unresolved reference: mockk and verify when i try to launch test any ideas?
    • 1
    • 1
  • m

    Mike

    04/24/2019, 2:14 PM
    @oleksiyp Don’t know if you saw the latest Thoughtworks Tech Radar. Congratulations on the ‘Adopt’ status! https://assets.thoughtworks.com/assets/technology-radar-vol-20-en.pdf
    🍾 1
    🎉 6
    o
    • 2
    • 1
  • i

    igorvd

    05/14/2019, 7:36 PM
    Is there an way to mock a function that receives a callback as parameter? For example, assuming that I have an assync operation, and the way to get the result is using an interface as callback. I want to unit test this method, defining responses in this callback. The problem lies in the fact that the callback is declared as anonymous (I will put an example below). Is possible to mock this callback and define its responses using MockK? Here is an example:
    class ViewModel {
    
    	fun loadSomeStuff() {
    		myObject.asyncOperation(object : Callback {
    			//callback methods implementation
    		})
    	}
    }
    I know if I change the callback for a parameter in my class, it will be easily mocked. But, in my opinion it doesn't make sense, because it's related to the operation I need in the method. (This example is just for learning purposes, I was trying to teach a colleague about unit tests, and I got stocked in this scenario)
    h
    • 2
    • 4
  • s

    Sergio Crespo Toubes

    05/16/2019, 12:49 PM
    Hello, exist a way with verify, check not all object parameters and only for example 3 parameters of 5? example
    verify(exactly = 1) { mView.loadUser(user is {name = "sergio"}) }
    and not
    verify(exactly = 1) { mView.loadUser(user)}
    o
    • 2
    • 17
  • s

    Sergio Crespo Toubes

    05/20/2019, 3:08 PM
    how can i mockk bitmap?
    l
    • 2
    • 22
  • o

    oleksiyp

    05/23/2019, 1:29 PM
    mockkStatic
    l
    • 2
    • 1
  • w

    wbertan

    05/23/2019, 2:07 PM
    You can use
    Instant.parse("2017-11-01T11:04:56Z")
    before the
    mockkStatic
    .
    p
    m
    +2
    • 5
    • 8
  • k

    kluck

    06/05/2019, 9:03 AM
    Hi, I'm trying to use
    verify(exactly = 1)
    inside a kotlintest
    BehaviorSpec
    , but it fails as it doesn't seem to be isolated from my other
    Given
    scope. Here's a basic example:
    Given("foo") {
      every { persistentSource.getAccessToken() } returns IO.raiseError(exception)
      When("") {
        [...] Then [...]
      }
    }
    Given("foo2") {
      every { persistentSource.getAccessToken() } returns IO { smartphonePersistedAccessToken }
      When("") {
        [...]
        Then("") {
          verify(exactly = 1) { persistentSource.getAccessToken() }
        }
      }
    }
    l
    • 2
    • 6
  • s

    svenjacobs

    06/12/2019, 9:57 AM
    Can someone please explain this behaviour to me?
    class CouponListInteractor(
        private val isCouponSelectedUseCase: IsCouponSelectedUseCase
    ) {
    
        suspend fun isCouponSelected(uuid: String) = isCouponSelectedUseCase.execute(uuid)
    }
    
    object CouponListInteractorTest : Spek(
        {
            val isCouponSelectedUseCase by memoized {
                mockk<IsCouponSelectedUseCase> {
                    coEvery { execute(any()) } returns false
                    coEvery { execute("uuid") } returns true
                }
            }
            
            val interactor = CouponListInteractor(
                isCouponSelectedUseCase
            )
    
            describe("CouponListInteractor") {
    
            context("isCouponSelected") {
    
                it("should return coupon selected state") {
                    runBlockingTest {
                        interactor.isCouponSelected("uuid") shouldEqual true
                    }
    
                    coVerify {
                        // ERROR: Bad recording sequence. State: AnsweringState 
                        isCouponSelectedUseCase.execute("uuid")
                    }
                }
            }
        }
    }
    coVerify
    produces
    Bad recording sequence. State: AnsweringState
    . However when I replace
    interactor.isCouponSelected("uuid") shouldEqual true
    with
    isCouponSelectedUseCase.execute("uuid") shouldEqual true
    the test runs.
    isCouponSelected()
    just delegates to the use case. I don't understand this behaviour? 🤯
    • 1
    • 1
  • s

    sdeleuze

    06/12/2019, 11:46 AM
    I am wondering if Mockk could be optimized when subclassing in not required and/or for
    open
    classes/methods where Mockito is significantly faster
    o
    • 2
    • 1
  • d

    Dariusz Kuc

    06/12/2019, 11:00 PM
    hello! it appears that it is not possible to capture arguments to mocked methods based on the other arguments - is that expected? e.g.
    class MockkCaptorTest {
    
        @Test
        fun `verify mockk captor behavior`() {
            val simpleMockk = mockk<Simple> {
                every { hello(any(), any()) } answers { "Mocked response for ${arg<String>(0)}, age: ${arg<Int>(1)}" }
            }
    
            simpleMockk.hello("Bob", 2)
            simpleMockk.hello("Alice", 1)
    
            val bobsAge = slot<Int>()
            verify {
                simpleMockk.hello("Bob", capture(bobsAge))
            }
            assertEquals(2, bobsAge.captured)
        }
    }
    
    class Simple {
        fun hello(name: String, age: Int) = "Hello $name, age: $age"
    }
    above will actually capture
    Alice
    age
    l
    • 2
    • 9
  • d

    Davide Giuseppe Farella

    06/16/2019, 3:00 PM
    Is there something wrong here? 😅
    o
    • 2
    • 5
  • m

    Matt Thompson

    06/17/2019, 11:00 PM
    anyone have an android project with both mockk and mockito? seems like upgrading mockk-android from 1.9 -> 1.9.1+ breaks mockito-android tests, but I'm not sure why. I've tried different combinations of versions, currently on the latest mockito 2.28.2, also forcing the transitive bytebuddy version (but I think both use 1.9.10 anyway) with no luck
    • 1
    • 1
  • a

    Artur Borowy

    06/18/2019, 9:13 AM
    Does anybody have idea, how to verify method with lambda argument? Sth like that.
    verify(exactly = 1, verifyBlock = { mock.method{ lambdaArgument() } })
    w
    • 2
    • 2
  • j

    Joan Colmenero

    07/03/2019, 7:31 PM
    I have a question if I have an
    attachView
    and
    detachView
    on my Presenter do I have to test these methods? Inside of the presenter I have the
    loadData
    and I have the unit tests for this
    loadData
    but then I have these methods and I don't know if I have to unit test those or not
    r
    • 2
    • 12
  • j

    Joram Visser

    07/09/2019, 10:54 AM
    I am struggling with mocking the
    foo
    and
    bar
    in this example. The code in the snippet is not working. I also tried making use of
    mockkConstructor()
    function for the
    ServiceLocator()
    ,
    Foo()
    and
    Bar()
    , which also didn’t work. So my question is; how can I set up the mocks correctly so that I can test
    MyClass
    without going out of the class.
    -.txt
    w
    • 2
    • 3
  • k

    Karolis

    07/15/2019, 8:59 AM
    val slot1 = slot<InvoiceLateFeeEntry>()
            verify {
                repo.save(capture(slot1))
            }
            val slot2 = slot<InvoiceLateFeeEntry>()
            verify {
                repo.save(capture(slot2))
            }
    slot1 == slot2, yet
    repo.save()
    was walled with different arguments
    • 1
    • 1
  • o

    oleksiyp

    07/17/2019, 6:57 AM
    Thanks, for the effort to detect it, right now I am busy on my main work, but every such submitted ticket is valuble
    d
    • 2
    • 1
  • o

    oleksiyp

    07/17/2019, 1:37 PM
    confirmVerified
    a
    • 2
    • 3
  • o

    oleksiyp

    07/17/2019, 2:31 PM
    I thought mockk mocks are strict by default, but mockito are not, but dont want to go deeper to compare it. Not near PC
    m
    a
    • 3
    • 17
  • a

    Anthony f

    07/18/2019, 2:24 PM
    Here is a sample of what I try to do, testing a locationmanager, that use PlayService component. There is a listener with a task, that I do not succeed to mock. Any help is welcome
    How_mockk_lambda.kt
    • 1
    • 1
  • b

    bbaldino

    07/25/2019, 5:42 PM
    i've got something like:
    private val dummyPacket = mockk<RtpPacket> {
            every { this@mockk getProperty "payloadType" } returns originalPayloadType
            every { this@mockk getProperty "ssrc" } returns originalSsrc
        }
    • 1
    • 3
  • l

    LeoColman

    08/10/2019, 1:17 PM
    You have to mock whatever is inside the inline call
    v
    • 2
    • 21
  • s

    svenjacobs

    08/14/2019, 1:40 PM
    Hi all, how can I mock a function type with MockK?
    val fn: () -> String? = mockk {
        // not working since "invoke()" clashes with invoke() function from MockK
        every { invoke() } returnsMany "hello", null
    }
    d
    o
    • 3
    • 3
  • a

    Anthony f

    08/23/2019, 2:20 PM
    @oleksiyp hello, could we specify the target of the @Mockk annotation, like @field:Mockk ? Will Mockk work correctly ?
    o
    • 2
    • 13
  • a

    Alessandro Tagliapietra

    08/27/2019, 6:41 AM
    Hello everyone, I'm using
    mockkObject
    to mock an object, since it's an object that makes external requests, is it possible to have the mocked version return an error if a method isn't mocked?
    m
    • 2
    • 5
  • o

    oleksiyp

    09/03/2019, 12:54 PM
    Check this doc section https://mockk.io/#verification-confirmation
    👏🏼 1
    i
    • 2
    • 1
  • t

    thanksforallthefish

    09/18/2019, 7:31 AM
    I know I read the answer somewhere, but how can I mock a method like
    fun updateParticipant(participant: Participant, update: Participant.() -> Unit)
    ? I am trying with
    val participantOrchestrationService: ParticipantOrchestrationService = mockk(relaxed = true)
    val dummy = Participant()
    val update = slot<Participant.() -> Unit>()
    every { participantOrchestrationService.updateParticipant(dummy) { capture(update) } } just Runs
    update.captured(dummy)
    dummy should {
    	it.state == State.inactive
    }
    but getting
    kotlin.UninitializedPropertyAccessException: lateinit property captured has not been initialized
    any suggestion?
    o
    • 2
    • 4
  • k

    Kamil K

    09/20/2019, 8:50 AM
    After updating AS to 3.5 all tests with 'mockk' are throwing NPEs. It looks like objects defined as mocks are actually calling real code. Is someone have similar issue? Is there a solution for it? I'm using kotlin
    1.3.2
    with
    mockk
    and
    mockk-android
    1.8.3
    o
    • 2
    • 2
Powered by Linen
Title
k

Kamil K

09/20/2019, 8:50 AM
After updating AS to 3.5 all tests with 'mockk' are throwing NPEs. It looks like objects defined as mocks are actually calling real code. Is someone have similar issue? Is there a solution for it? I'm using kotlin
1.3.2
with
mockk
and
mockk-android
1.8.3
o

oleg_osipenko

09/20/2019, 9:23 AM
I had. Fixed adding dexopener to my test runner https://github.com/tmurakami/dexopener
k

Kamil K

09/23/2019, 9:50 AM
Any idea what is causing the problem?
View count: 16