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

    arild

    09/23/2019, 1:12 PM
    Could I solicit some opinions on
    private val someMockedDependency: SomeClass = mockk()
    vs
    @MockK private lateinit var someMockedDependency: SomeClass
    ?
    w
    • 2
    • 3
  • b

    Big Chungus

    10/01/2019, 8:32 AM
    Hello, is there a way to mock this interface in common module:
    external interface DElement : DNode {
    }
    • 1
    • 1
  • c

    Cody Engel

    10/08/2019, 10:45 PM
    What’s the difference between
    clearAllMocks
    and
    unmockkAll
    ? I have the following test rule and when I used
    clearAllMocks
    in the finished function I was seeing some tests failing because a
    mockkObject
    wasn’t being cleared. With
    unmockkAll
    though it resolved the issue.
    class MockKTestRule(private val target: Any) : TestWatcher() {
        override fun starting(description: Description?) {
            super.starting(description)
            MockKAnnotations.init(target)
        }
    
        override fun finished(description: Description?) {
            unmockkAll() // clearAllMocks doesn't work for all use cases
            super.finished(description)
        }
    }
    But I don’t understand what the difference is? When would I want to use
    clearAllMocks
    over
    unmockkAll
    ?
    • 1
    • 1
  • r

    rkeazor

    10/17/2019, 1:49 AM
    Can mockk mock channels
    d
    • 2
    • 2
  • y

    Yeray Cabello

    10/23/2019, 6:54 AM
    Hi, I'm trying to mock a static method that takes a
    () -> Unit
    function as a parameter, but the matchers seem not to be able to get the mocking signature:
    io.mockk.MockKException: Failed matching mocking signature for
    
    left matchers: [any()]
    What am I missing? I know that equality with lambdas can be a nightmare, but can't seem to find documentation on this.
    Untitled.kt
    • 1
    • 2
  • p

    poohbar

    10/30/2019, 1:28 PM
    @Before
    fun setup() {
    
    val instant = Instant.ofEpochMilli(1572400000000)
    mockkStatic(Instant::class) {
        every { Instant.now() } returns instant
    }
    
    }
    d
    • 2
    • 3
  • d

    Dennis Schröder

    11/04/2019, 3:18 PM
    Is it possible to mock inner Classes yet?
    o
    • 2
    • 2
  • l

    LeoColman

    11/20/2019, 4:16 PM
    Yeah, this smells bad code all over it, but it's for legacy code that I want well tested before I refactor
    c
    • 2
    • 1
  • s

    Samuel Michael

    11/20/2019, 9:37 PM
    Im new to mockkito so this is probably a dumb question but how do i avoid this?
    l
    r
    c
    • 4
    • 9
  • m

    Mark McCormick

    11/27/2019, 3:13 PM
    Hey guys 👋 I have some logic inside the
    init
    block in my
    ViewModel
    . I would like to set some expected behavior of a mock I have inside the
    init
    block like this
    every { repository.getSomething() } returns SomeEnum.A
    . The problem is this expected answer is executed after the
    init
    block. If I put the
    every { ... }
    part to
    @Before
    function it works fine, but I would like to set this expected answer only for one specific test. Any ideas?
    • 1
    • 1
  • a

    alostpacket

    12/23/2019, 2:53 AM
    @antoniomarin what happens if you replace
    any<String>()
    with just
    String
    a
    • 2
    • 1
  • k

    Kris Wong

    12/23/2019, 8:14 PM
    has anyone seen this before?
    Untitled
    • 1
    • 2
  • k

    kyleg

    12/25/2019, 8:10 PM
    Aha. If I have top-level
    foo: (File)->Long
    I want to mock, and top-level (same file)
    caller: (foo: (File)->Long)->Int
    that I do not want to mock, then that file needs
    @file:JvmName("FooKt") ; package <http://path.to|path.to>
    up top, and then in the test:
    with(::caller) {
                mockkStatic("path.to.FooKt")
                every { foo(any()) } returns 0L
    
                this(::foo)
    
                verify { foo(File("/path/to/thing") }
            }
    k
    • 2
    • 5
  • a

    antoniomarin

    01/16/2020, 1:38 PM
    Hi all, beginner question here. Is it possible that production code method changes mock? I’ve got following:
    // PRODUCTION
    class classUnderTest(
        private val preferences: Preferences
    ) {
    
        fun changePreferenceToTrue() {
            preferences.somePreference = true        
        }
    }
    
    // TEST
    @Test
    fun `Given preference false when changePreferenceToTrue then check is preference updated`() {
        every { preferences.somePreference } returns false
    
        classUnderTest.changePreferenceToTrue()
        
        // I want to assert that this Preference is true
        print(preferences.somePreference) // always returns as defined above, in this case false
    }
    m
    • 2
    • 5
  • v

    voben

    01/23/2020, 4:47 AM
    What’s the difference between using
    every {} returns something
    and
    every {} answers {something}
    s
    v
    +3
    • 6
    • 6
  • v

    voben

    02/08/2020, 8:51 PM
    I’m trying to test my repo which looks something like this. The issue is I’m not quite sure how to deal with the FirebaseInstanceId. Is this something I can mock, if so how would I do that?
    class Repository(private val service: RetrofitService) {
    
        suspend fun sendToken() {
            val result = FirebaseInstanceId.getInstance().instanceId.await()
            service.sendTokenToServer(result.token)
        }
    
    }
    t
    o
    +2
    • 5
    • 6
  • i

    ivano

    02/14/2020, 2:28 PM
    I get an error because the implementation expects that the data class is parcelable, and I cannot mock the @Parcelize
    g
    • 2
    • 4
  • j

    John Gainfort

    02/25/2020, 11:10 PM
    java.lang.ExceptionInInitializerError
    	at scte35decoder.Scte35DecoderTests.mockBase64Decoder(Scte35DecoderTests.kt:44)
    	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    	at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    	at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    	at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:110)
    	at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:58)
    	at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:38)
    	at org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:62)
    	at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
    	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    	at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    	at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    	at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    	at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    	at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    	at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
    	at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:118)
    	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    	at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    	at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    	at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    	at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
    	at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
    	at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:412)
    	at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    	at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    	at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
    	at java.base/java.lang.Thread.run(Thread.java:834)
    Caused by: java.lang.IllegalStateException: Error during attachment using: net.bytebuddy.agent.ByteBuddyAgent$AttachmentProvider$Compound@49aca0a6
    	at net.bytebuddy.agent.ByteBuddyAgent.install(ByteBuddyAgent.java:427)
    	at net.bytebuddy.agent.ByteBuddyAgent.install(ByteBuddyAgent.java:401)
    	at net.bytebuddy.agent.ByteBuddyAgent.install(ByteBuddyAgent.java:353)
    	at net.bytebuddy.agent.ByteBuddyAgent.install(ByteBuddyAgent.java:330)
    	at io.mockk.proxy.jvm.JvmMockKAgentFactory.initInstrumentation(JvmMockKAgentFactory.kt:134)
    	at io.mockk.proxy.jvm.JvmMockKAgentFactory.init(JvmMockKAgentFactory.kt:34)
    	at io.mockk.impl.JvmMockKGateway.<init>(JvmMockKGateway.kt:46)
    	at io.mockk.impl.JvmMockKGateway.<clinit>(JvmMockKGateway.kt:172)
    	... 48 more
    Caused by: <http://java.io|java.io>.IOException: Cannot run program ""/Applications/IntelliJ IDEA <http://CE.app/Contents/jbr/Contents/Home/bin/java%22%22|CE.app/Contents/jbr/Contents/Home/bin/java"">: error=2, No such file or directory
    	at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1128)
    	at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1071)
    	at net.bytebuddy.agent.ByteBuddyAgent.installExternal(ByteBuddyAgent.java:485)
    	at net.bytebuddy.agent.ByteBuddyAgent.install(ByteBuddyAgent.java:420)
    	... 55 more
    Caused by: <http://java.io|java.io>.IOException: error=2, No such file or directory
    	at java.base/java.lang.ProcessImpl.forkAndExec(Native Method)
    	at java.base/java.lang.ProcessImpl.<init>(ProcessImpl.java:340)
    	at java.base/java.lang.ProcessImpl.start(ProcessImpl.java:271)
    	at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1107)
    	... 58 more
    k
    • 2
    • 12
  • j

    John Gainfort

    02/25/2020, 11:10 PM
    Im trying to use Mockk with a Kotlin Multi Platform library that I am making. However I can’t seem to get it to work. In my commonMain I have an interface defined
    interface Foo { fun bar(val: String): ByteArray }
    then in my commonTest I am trying to mock Foo
    val mockedFoo = mockk<Foo> { every { bar("test") } returns ByteArray(1) }
    my build.gradle.kts has
    val commonTest by getting {
                dependencies {
                    implementation(kotlin("test-common"))
                    implementation(kotlin("test-annotations-common"))
                    implementation("io.mockk:mockk:1.9.3")
                    implementation("io.mockk:mockk-common:1.9.3")
                }
            }
    but when I go to run a test I get this error that I am having a hard time figuring out.
    • 1
    • 1
  • j

    Joan Colmenero

    03/03/2020, 11:53 AM
    I'm trying to remove the
    withContext
    from my viewModel and I'm planning to put it on the
    usecase
    /
    repository
    something like this
    launch{
     updateView()
     withContext(<http://Dispatchers.IO|Dispatchers.IO>){
       doLogin(username,password)
     }
     updateView()
    }
    This is how I'm doing it now ^ Then if I want to remove the
    withContext(<http://Dispatchers.IO|Dispatchers.IO>)
    I can do it like this
    suspend fun doLogin(usernarme: String, password: String) = <http://Dispatchers.IO|Dispatchers.IO> { repo.doLogin(username,password)... }
    So, is there any way to test it correctly? I'm using
    mockK
    so, I know with
    coEvery
    is going to work, but is it safe to do not put
    Dispatchers.Uncofined
    for testing purposes? Also do you think it's a good idea to do not change context on viewModel and then just do this
    launch {
     updateView()
     doLogin(username,password)
     updateView()
    }
    s
    • 2
    • 3
  • k

    Kris Wong

    03/04/2020, 6:52 PM
    i see it's been a year since the last release. is this project dead?
    o
    j
    • 3
    • 16
  • k

    Kulwinder Singh

    03/10/2020, 1:30 PM
    for MockK, i'm getting
    MockKException: no answer found for: MyClass(#1).sendMessage(okhttp3.RequestBody$2@4ed4bd33)
    , actually RequestBody's properties are same just instance is different. that's why it did not matches parameters but if i add
    any()
    instead of requestbody it works. is there anything else i can use instead of
    any()
    here ?
    every {	myClass.sendMessage(MockRequest.createTestBody(value="text")) } answers { something }
    
    ....
    
    class SomeObject(myClass:MyClass){
    	fun doSomething(text: String): Flowable<Result<Boolean>> {
            val request = MockRequest.createTestBody(text)
    		myClass.sendMessage(request)
    	}
    }
    ....
    i have checked documentation of mockk but didn't found anything, that's why asked here:
    c
    • 2
    • 26
  • e

    Erik

    03/19/2020, 5:33 PM
    Latest stable releases of mockk-patterns: - For JUnit 4 (e.g. Android):
    testImplementation("com.github.erikhuizinga:mockk-junit4:1.0.0")
    - For JUnit 5:
    testImplementation("com.github.erikhuizinga:mockk-junit5:2.0.0")
    - For kotest a PR has been opened by @Sourabh Rawat, which I've reviewed.
    s
    • 2
    • 1
  • e

    Ellen Spertus

    03/25/2020, 12:15 AM
    I’m having a problem with MockK and JUnit5 in Android development. Here is my code:
    private fun makeResolveInfo(appName: String, packageName: String, exported: Boolean = true) :
        ResolveInfo {
      val activityInfo = mockk<ActivityInfo>()
      every { activityInfo.exported } returns exported
      // remaining code omitted
    The program crashes on the line with
    every
    :
    io.mockk.MockKException: Missing calls inside every { ... } block.
    	at io.mockk.impl.recording.states.StubbingState.checkMissingCalls(StubbingState.kt:14)
    	at io.mockk.impl.recording.states.StubbingState.recordingDone(StubbingState.kt:8)
    	at io.mockk.impl.recording.CommonCallRecorder.done(CommonCallRecorder.kt:47)
    	at io.mockk.impl.eval.RecordedBlockEvaluator.record(RecordedBlockEvaluator.kt:60)
    	at io.mockk.impl.eval.EveryBlockEvaluator.every(EveryBlockEvaluator.kt:30)
    	at io.mockk.MockKDsl.internalEvery(API.kt:92)
    	at io.mockk.MockKKt.every(MockK.kt:104)
    	at mozilla.voice.assistant.intents.MetadataTest$Companion.makeResolveInfo(MetadataTest.kt:61)
    Any idea what I’m doing wrong? The file is in a
    test
    directory rather than
    androidTest
    . I don’t know if that could be a problem.
    s
    m
    • 3
    • 6
  • d

    Dave Leeds

    03/27/2020, 8:29 PM
    Hey all. I’m looking for ways to mock Ktor’s HttpClient with mockk for unit tests. I’ve tried the usual approach:
    coEvery { httpClient.hint(MyPayload::class).get<MyPayload>(any<String>()) }.returns(examplePayload)
    But this fails with a class cast exception:
    MyPayload cannot be cast to io.ktor.client.call.HttpClientCall
    I suspect the reason for this is that the entire call stack between the test and
    HttpStatement.executeUnsafe()
    is made up of
    inline
    functions. I tried to mock
    httpClient.execute()
    since that’s ultimately what gets invoked, but that’s marked as
    @InternalAPI
    . Any ideas?
    r
    • 2
    • 4
  • k

    Kris Wong

    04/22/2020, 6:37 PM
    I am having a strange issue with an object mock. given:
    mockkObject(AppLockedState)
            every { AppLockedState.isLocked() } answers { locked }
    it seems to be executing the
    isLocked
    method rather than using the answer. it's complaining that Boolean can't be cast to one of the types being used in the method implementation
    o
    • 2
    • 6
  • k

    Kris Wong

    04/23/2020, 2:11 PM
    how am I supposed to mock methods that take complex/abstract types, or types that expect certain properties to be non-null, etc...?
    • 1
    • 1
  • k

    Kris Wong

    04/23/2020, 2:22 PM
    mockkObject(IntentQueueFactory)
            every { IntentQueueFactory.getInstance(context) } returns queue
    causes
    io.mockk.MockKException: Missing calls inside every { ... } block.
    at io.mockk.impl.recording.states.StubbingState.checkMissingCalls(StubbingState.kt:14)
    at io.mockk.impl.recording.states.StubbingState.recordingDone(StubbingState.kt:8)
    at io.mockk.impl.recording.CommonCallRecorder.done(CommonCallRecorder.kt:47)
    at io.mockk.impl.eval.RecordedBlockEvaluator.record(RecordedBlockEvaluator.kt:60)
    at io.mockk.impl.eval.EveryBlockEvaluator.every(EveryBlockEvaluator.kt:30)
    at io.mockk.MockKDsl.internalEvery(API.kt:92)
    at io.mockk.MockKKt.every(MockK.kt:98)
    • 1
    • 1
  • k

    Kris Wong

    04/23/2020, 2:55 PM
    I found this framework to be pretty interesting when getting started with it, but unless I am missing something here, it doesn't seem to support anything beyond the most basic use cases
    o
    m
    • 3
    • 14
  • a

    Alex Kuznetsov

    05/01/2020, 5:59 PM
    Is there a way to have a multi-line
    mockk
    statement: I'd like to spread a long statement like the following over several lines:
    every { <http://myThing.do|myThing.do>() } returns 1 andThenThrows Exception("No way!") andThen 3 andThen 4
    the line gets too wide, is there a way to continue it:
    every { <http://myThing.do|myThing.do>() } returns 1 
      andThenThrows Exception("No way!") 
      andThen 3 
      andThen 4
    TIA!
    j
    • 2
    • 2
Powered by Linen
Title
a

Alex Kuznetsov

05/01/2020, 5:59 PM
Is there a way to have a multi-line
mockk
statement: I'd like to spread a long statement like the following over several lines:
every { <http://myThing.do|myThing.do>() } returns 1 andThenThrows Exception("No way!") andThen 3 andThen 4
the line gets too wide, is there a way to continue it:
every { <http://myThing.do|myThing.do>() } returns 1 
  andThenThrows Exception("No way!") 
  andThen 3 
  andThen 4
TIA!
j

jdiaz

05/02/2020, 7:32 PM
There's no way to do it with infix functions but iirc you can still use the dot notation like
returns(1).andThenThrows(...).andThen(3)
and then you can format it as you want
👍 1
a

Alex Kuznetsov

05/18/2020, 9:35 PM
@jdiaz thanks a lot
View count: 26