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

    Helio

    01/15/2021, 9:46 PM
    Hello guys! I was wondering here if any of you have already mocked Ktor HttpResponse. I've tried as the following. Do you have any suggestion? https://kotlinlang.slack.com/archives/C0A974TJ9/p1610688463022200
    c
    • 2
    • 9
  • p

    Patrick Ramsey

    02/11/2021, 10:18 PM
    Possibly a dumb question, but does anyone here happen to know if there’s a way to mock constructors that doesn’t result in the underlying class’s real constructor actually being called?  From what I can tell (somewhat astonishingly), the default behavior of mockkConstructor() is to actually call a real constructor, then discard its output and substitute a mockk singleton.  This is somewhat disappointing, since it suggests that you can’t actually mock constructors with mockkConstructor() (ie, that unwanted side-effects will still occur)
    e
    • 2
    • 2
  • m

    Mattia Tommasone

    02/11/2021, 10:22 PM
    that’s a tricky one and there’s an open issue about it AFAIR. The thing is mockk still needs to somehow instantiate an instance of the class and thus execute a constructor. The bad answer to your question, then, is that ideally your constructors should not have side effects; a possible workaround could be to put them in a @PostConstruct method
    p
    e
    c
    • 4
    • 18
  • m

    Mattia Tommasone

    02/13/2021, 2:57 PM
    1.10.6
    has just been released: it has a good number of bugfixes, feel free to check it out!
    🎉 5
    👏 3
    n
    • 2
    • 2
  • v

    vio

    03/02/2021, 1:11 PM
    Hi all! I am using mockk for tests but keeps failing to mock the calls that I expect, when I try running all tests from cli (with gradle:
    gradle :test
    ). when run individually with
    kotest
    runs perfectly. I have something like this:
    beforeSpec {
      Application.start()
      mockkObject(MyObjectClass)
      every { MyObjectClass.getRandomString() } returns "call made"
    })
    
    afterSpec {
       clearAllMocks()
       Application.stop()
    }
    
    ....
    // some other tests that should make calls to the function that I mocked above
    
    "verify mockk" {
       verify(exactly = 7) {
            MyObjectClass.getRandomString()
       }
    }
    I can't figure out what could be wrong here, I get this error when run from the command line :
    java.lang.AssertionError: Verification failed: call 1 of 1: MyObjectClass(object MyObjectClass).getRandomString()) was not called  .......
    Any help is appreciated, thank you! 🙏
    m
    s
    • 3
    • 10
  • m

    Melih Aksoy

    03/04/2021, 3:49 PM
    Hi everyone ! Is it possible to test following piece of code via mocks ?
    process
        .inputStream
        .bufferedReader()
        .useLines { seq ->
            val summary = seq.find { line -> line.contains(KEY_PACKET_LOSS) }
    
            if (summary != null) {
                val loss = packetLoss(summary)
    
                val result = when {
                    loss > acceptablePacketLoss -> Stability.UNSTABLE
                    loss == MAX_LOSS -> Stability.NO_CONNECTION
                    else -> Stability.STABLE
                }
    
                continuation.resumeIfActive(result)
            } else {
                continuation.resumeWithExceptionIfActive(
                    IllegalStateException("Couldn't find result line in ping command")
                )
            }
        }
    I added required statics, but
    bufferedReader
    and
    useLines
    are inline methods… can I work this around somehow ?
    m
    c
    • 3
    • 3
  • d

    Daniele Andreoli

    03/09/2021, 9:42 PM
    Good evening. Sadly, i'm not good at testing and I need some help. I'm trying to use mockk to mock my Retrofit API response. I?m trying to do as follow:
    Response.success(mockedResponseList)
    Here's the code complete:
    coEvery { restApi.getAllBeersWithPagination(1, null).hint(Response::class) } coAnswers { Response.success(mockedResponseList)}
    But it always returns:
    java.lang.ClassCastException: java.lang.Object cannot be cast to retrofit2.Response
    Someone can help me, please? Thanks
    m
    • 2
    • 4
  • l

    Luiz Aguiar

    03/20/2021, 11:30 AM
    hello folks given the function:
    fun <T : Any> myFunction(foo: Foo, bar: Bar, response: KClass<T>): MyResponse<T> { do magic }
    how can it be mocked to control the returned object? I tried something like:
    every { mockedClass.myFunction(any(), any(), ofType(SomeType::class) } returns SomeType()
    but it didn't work... and using the type directly,
    myFunction(any(), any(), SomeType::class)
    is never matched.
    e
    • 2
    • 4
  • m

    Mattia Tommasone

    04/08/2021, 2:47 PM
    uhm not sure i understand what you’re trying to achieve do you want to return a different employeeAttribute depending on the value of the parameter being passed to getEmployee?
    i
    m
    • 3
    • 15
  • i

    ivano

    04/08/2021, 2:55 PM
    and the fun `
    private fun getEmployees(users: List<String>)
    takes a list that(also I mocked) which has two values “1” and “3"
    :thread-please: 2
    m
    • 2
    • 1
  • p

    Patrick Ramsey

    04/13/2021, 5:26 AM
    Say I have a verify block like this:
    verify {
        someMethod(capture(mySlot), "Some specific value")
    }
    Is there any way to actually just capture the value from when someMethod() was called with “Some specific value”? Or will that capture() match every single call, even the ones where the whole expression doesn’t match?
    e
    m
    • 3
    • 31
  • s

    Sergio Crespo Toubes

    04/13/2021, 10:50 AM
    Hello, i am getting error with args and i dont know what is the solution.
    answers {
        thirdArg<(String) -> Unit>().invoke("text")
    }
    i had to change it to
    answers {
        thirdArg<(String) -> Boolean>().invoke("text")
    }
    but i am getting the next solution
    Unit cannot be cast to java.lang.Boolean
    any idea? thanks
    m
    e
    • 3
    • 14
  • i

    ivano

    04/20/2021, 2:53 PM
    Hi, sorry to ask another time help after one week, at least I will write everything on the same thread. I have to test a function to ascertain that returns a type. I am using firebase initialising via an Object the function that calls FirebaseAnalytics
    object AnalyticsReporter {
    
        fun logEvent(message: String, bundle: Bundle = Bundle.EMPTY) {
    
            FirebaseAnalytics.getInstance(ProActiveApplication.applicationContext()).logEvent(message, bundle)
        }
    the method i call is this one :
    when (loginState.value) {
           
                is EnterPassword -> {
                    unknownPassword.onNext(AuthenticationCredentials(client, emailAddress))
                    logEvent("user_forgot_password")
                }
    }
    m
    m
    • 3
    • 24
  • p

    poohbar

    04/20/2021, 8:10 PM
    hey guys, I really really need a way to create a mockk from within Java code.. is there any way to do it?
    🇳🇴 1
    m
    m
    • 3
    • 2
  • a

    Anton Afanasev

    05/06/2021, 4:50 PM
    Hi guys and gals! Have a silly question, but would like to get your opinion. How you decide whether use spyk or mockk? When you would prefer one on top of another?
    m
    c
    d
    • 4
    • 34
  • a

    Anton Afanasev

    05/07/2021, 2:59 PM
    Hi again! I did not find any related thread on this channel, so will ask. When I am doing some sequence verification and one of the call arguments does not match - I get:
    Verification failed: calls are not exactly matching verification sequence
    which is fine. However the error message is not descriptive. It points to the high level problem (something wrong with whole sequence) instead of saying something like: "Hey, your sequence failed because of argument matching here" Are there a way to get more descriptive message when something like that happens? Is it me that incorrectly structure the test. Attaching simplified version of the test:
    @Test
        fun `when connect`() {
            // When
            subject.connect()
    
            // Then
            verifySequence {
                mockStateListener(State.CONNECTING)
                mockPlatformSocket.openSocket(any())
            }
        }
    And the error:
    Verification failed: calls are not exactly matching verification sequence
    
    Matchers: 
    Function1(#1).invoke(eq(CONNECTING)))
    +PlatformSocket(#2).openSocket())
    
    Calls:
    1) Function1(#1).invoke(CONNECTED)
    2) +PlatformSocket(#2).openSocket()
    
    Stack traces:
    m
    • 2
    • 5
  • a

    André Thiele

    05/09/2021, 3:37 PM
    Is it possible to only verify a function call but ignore the specific instance that a mocked function is being called with?
    e
    • 2
    • 2
  • p

    Peter Ertl

    05/18/2021, 11:49 AM
    does anybody know if mockk v1.11.0 supports mocking inline value classes? it seems it does not…
    m
    • 2
    • 5
  • p

    Patrick Ramsey

    05/18/2021, 5:11 PM
    I just wrote a bunch of tests, that passed just fine on java 8, but when I ran them on java 11 (which is what our build box has) I got this warning:
    WARNING: An illegal reflective access operation has occurred
    WARNING: Illegal reflective access using Lookup on io.mockk.proxy.jvm.ClassLoadingStrategyChooser (file:/home/circleci/.gradle/caches/transforms-2/files-2.1/5bf8247b5024cc1f3e5041b83c85dfb2/jetified-mockk-agent-jvm-1.10.6.jar) to class javax.xml.parsers.DocumentBuilder
    WARNING: Please consider reporting this to the maintainers of io.mockk.proxy.jvm.ClassLoadingStrategyChooser
    WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
    WARNING: All illegal access operations will be denied in a future release
    Not sure if it’s related, but four tests then fail with NoClassDefFoundException: io/mockk/proxy/jvm/advice/jvm/JvmMockKProxyInterceptor
    • 1
    • 6
  • a

    Anton Afanasev

    05/19/2021, 2:06 PM
    Hi. I am working on mobile kmm project. (ios + android) As per my understanding there is no way right now to import mockk into commonTest module, as it targets kotlin native as well. I am wondering: 1. Am I wrong? 2. What is the idea of io.mockk:mockk-common then? The documentation reference this dependency for Common Multiplatform.
    b
    c
    • 3
    • 9
  • e

    eurycea

    05/21/2021, 1:37 PM
    Is anyone successfully running an Espresso KoinTest that injects a mocked (with mockk) ViewModel via stateViewModel? Is there a trick to getting around getTag needing to return SavedStateHandleController? I am using koin 3.0.1 and mock 1.11.0
    j
    • 2
    • 3
  • r

    Robert MacLean

    05/27/2021, 8:41 AM
    Hi, Is there a difference between
    mockk<T>(relaxed = true)
    vs.
    spyk
    ? I tend to think of them as the same and use the former is useful for when there is a default constructor and the the latter if I need to pass properties to a constructor, and otherwise think they end up the same…. but maybe I am wrong?
    m
    t
    • 3
    • 5
  • s

    Sourabh Rawat

    06/01/2021, 4:08 AM
    Getting
    Caused by: io.mockk.MockKException: Failed matching mocking signature for
    SignedCall(retValue=java.lang.Object@32bb09d9, isRetValueMock=true, retType=class kotlin.Any, self=UseCase(#25), method=execute(Any, Continuation), args=[kotlin.Unit, Continuation at com.expediagroup.ord.fbs.usecase.UseCaseExecutorTest$2$1.invokeSuspend(UseCaseExecutorTest.kt:47)], invocationStr=UseCase(#25).execute(kotlin.Unit, continuation {}))
    left matchers: [any()]
    what could be the issue…
    m
    • 2
    • 1
  • e

    Emil Kantis

    06/01/2021, 8:45 PM
    Hi, I just ran into a very tricky problem. I had a mock of an extension function from a test which ended up recording millions of method calls, which ultimately led the test execution to hang completely. In my case I had also forgot to clear mocks at one point, which made the hang happen in a completely different test which didn't make it obvious that the problem was related to a mock at all. Posting here to get some input before possibly filing an issue on 😮ctocat: I think it would be reasonable that mockk had a (configurable) cap of the amount of recorded invocations, and any further calls throws an exception. The cap should be sufficiently low to not cause an extreme slowdown of tests before throwing exception.
    m
    • 2
    • 6
  • p

    Patrick Ramsey

    06/04/2021, 7:32 PM
    I just added a dependency which pulled in slf4j and slf4j-android into my kotlin android project. It looks like JvmMockKGateway.Companion logs from its init {} block, and if slf4j is present, it uses slf4j. And with the slf4j-android binding present, slf4j will call into android.util.Log, which will raise an assertion error if it’s called from a unit test, when unmocked, resulting in an exception, resulting in a NoClassDefFoundError for JvmMockKGateway.
    e
    • 2
    • 35
  • p

    Patrick Ramsey

    06/04/2021, 7:32 PM
    is there a way to work around this? And/or, am I doing something dumb? 😛
    • 1
    • 2
  • e

    Emil Kantis

    06/10/2021, 7:28 PM
    Setting up a mock like this causes problems because the x in every will not refer to the x on the mocked
    Point
    data class Point(val x: Int, val y: Int) 
    
    val x = 7
    val mockPoint = mockk<Point> { 
      every { x } returns x
    }
    If the receiver in the
    every
    block would be <T> (or Point in this case), I believe x would bind correctly, but perhaps that causes other issues?
    k
    • 2
    • 1
  • a

    Anton Afanasev

    06/23/2021, 1:07 PM
    Hello there! As far as I see in mockk documentation Inline functions cannot be mocked: https://github.com/mockk/mockk/issues/27 This issue is dated 2018. Wondering if anything has changed since then?
    e
    m
    • 3
    • 2
  • m

    mkrussel

    06/29/2021, 1:16 AM
    I'm trying to mock private properties from in a companion object. When I run the tests they throw an exception.
    io.mockk.MockKException: can't find property workerHandler for dynamic property get
    Untitled.cpp
    m
    • 2
    • 4
  • m

    Mark Allanson

    06/29/2021, 8:20 AM
    Is there any way to make a
    spyk
    intercept all calls to object AND make it relaxed at the same time?
    m
    • 2
    • 19
Powered by Linen
Title
m

Mark Allanson

06/29/2021, 8:20 AM
Is there any way to make a
spyk
intercept all calls to object AND make it relaxed at the same time?
m

Mattia Tommasone

06/29/2021, 8:24 AM
Do you have a use case of what you would like to do?
m

Mark Allanson

06/29/2021, 8:31 AM
I've got a class that wraps a generic type and am trying to write a spring test that sucks up all these "classes that need to be wrapped", wraps them and tests that the wrapping class does the right thing So I have something like...
class Dispatcher(val wrapped: SomeClass<*>)
I essentially want to do (where toBeWrapped is injected via spring to the test)....
@SpringBootTest
class DispatcherTests {
    @Autowired
    lateinit var toBeWrapped: List<ProviderModule<*, *>>

    @Test
    fun testGetDataDispatchedForEachProvider() {
        for (dispatcher in this.toBeWrapped.map { Dispatcher(it) }) {
            val moduleSpy = spyk(dispatcher.provider)
            every { moduleSpy.getData(any()) }
            dispatcher.getData(someData)
            verify { moduleSpy.getData(any()) }
        }
    }
}
of course the call to
getData
on
toBeWrapped
could be anything, which is represented as
Nothing
by the compiler, so am having trouble spying on it
(I know this scenario is a nightmare, but I am working with a protobuf
oneof
which makes it messy)
m

Mattia Tommasone

06/29/2021, 8:32 AM
ow, that’s a nightmare indeed 😄
m

Mark Allanson

06/29/2021, 8:33 AM
Essentially I am trying to verify that when a new one of the
toBeWrapped
classes are added, that a mapping is also added into the
Dispatcher
component
m

Mattia Tommasone

06/29/2021, 8:33 AM
i think the best shot you can have at making it better would be to somewhat constrain the generic types, i.e. making them
* extends Something
rather than just
*
so that you can have your spied getData return something better than Nothing
does it make sense to you?
m

Mark Allanson

06/29/2021, 8:33 AM
yeah unfortunately protobuf messages (hence classes generated) cannot inherit
m

Mattia Tommasone

06/29/2021, 8:34 AM
oh, right 😞
m

Mark Allanson

06/29/2021, 8:34 AM
Oh hang on - maybe they do actually, from a generic protobuf message class
oh great they do!
public final class SomeCalss extends GeneratedMessageV3
Good outside the box thinking :D
m

Mattia Tommasone

06/29/2021, 8:35 AM
nice 🙂
m

Mark Allanson

06/29/2021, 11:14 AM
So this doesn't work as one of the generic parameters is contravariant so convert to Nothing anyway even with an extends. From the kotlin docs
For
Foo<in T>
, where
T
is a contravariant type parameter,
Foo<*>
is equivalent to
Foo<in Nothing>
. It means there is nothing you can write to
Foo<*>
in a safe way when
T
is unknown.
m

Mattia Tommasone

06/29/2021, 11:22 AM
ouch
m

Mark Allanson

06/29/2021, 2:31 PM
Ok I got success with dynamic calls mocking
every { 
  dispatcherSpy invoke "dispatch" withArguments listOf(a, b) 
} returns response
m

Mattia Tommasone

06/29/2021, 2:32 PM
uh, nice!
m

Mark Allanson

06/29/2021, 2:48 PM
Ah the discovery continues, creating a relaxed mock from a class is also possible, and nicer.
mockkClass(theClassInstance::class, relaxed = true)
View count: 11