Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Activity
    Will Fisher
    @wafisher
    @senioroman4uk how did you get your local project to build against a local version of mockk? do you mind describing the changes you made to settings.gradle and build.gradle to get it to build?
    J├╝rgen Landgraf
    @DonJogi
    Hi all, I'm using mockk on Android and tried to upgrade the Android Gradle plugin recently, from 3.5.x to 3.6.x, and also the new 4.0.0. After upgrading I always run into the issue "MockK could not self-attach a jvmti agent to the current VM." described in this issue: mockk/mockk#297
    To me it looks like mockk cannot be used with the new Android Gradle plugin at all, if I'm not doing something wrong. Has anybody managed to get that working, or is there any way I could help to fix this issue?
    Vladyslav
    @senioroman4uk
    hi @wafisher sorry for the late reply. This is the patch with changes that I did in order to build the project
    Will Fisher
    @wafisher
    Awesome, thanks!
    Sebastian Schuberth
    @sschuberth
    Hi everybody, I'm new to mockk, and also quite new to the concept of mocking in general, so please excuse if I make wrong assumptions. But I cannot get verfiy() to as expected work on a spied object. verfiy() succeeds if I call the function direcctly, but not if I call another function on the spied object that internally calls the verified function. Is this expected? The code is at https://github.com/oss-review-toolkit/ort/commit/ecb6806bd2e56a0aed5e828f23a3e2177d00aecb#diff-deb71474e3d9ce4826f934d16e73b0e1R60-R64
    Sebastian Schuberth
    @sschuberth
    Nevermind, I found I was indeed verifying the wrong function. I believe to have fixed that now, but now I'm running into a stack overflow error: https://github.com/oss-review-toolkit/ort/commit/c354c9569c2765d78003833454d0b9e35c456a5f#diff-deb71474e3d9ce4826f934d16e73b0e1R63-R64
    Sebastian Schuberth
    @sschuberth
    I guess I could be affected by mockk/mockk#366. Can anyone confirm my case is the same as the one in the ticket?
    Sebastian Schuberth
    @sschuberth
    Actually, looking at the stack trace again it seems I'm rather affected by mockk/mockk#273, which luckily already has a proposed fix at mockk/mockk#444.
    Mohammad M. Ahmad
    @mmahmad

    Hi!

    I would like to capture the arguments of a method but then let the method run as-is. The objective is to verify the output with the expected output, but I would like to used the captured argument to compute the expected output myself, instead of mocking anything.

    Is that possible?

    Mohammad M. Ahmad
    @mmahmad

    Hi!

    I would like to capture the arguments of a method but then let the method run as-is. The objective is to verify the output with the expected output, but I would like to used the captured argument to compute the expected output myself, instead of mocking anything.

    Is that possible?

    Something like:

    val captured_arg: slot<List<JobDetails>>()
    coEvery { myClass.myMethod(capture(captured_arg)) } runs myClass.myMethod(captured_arg.captured)  // the method returns a List<JobDetails> which I want to verify once `myClass.myMethod()` runs as it would
    
    // beginApp() called to run the code from beginning to end
    
    // verify some things about the returned result of myClass.myMethod() after computing some things on captured_arg myself here
    Vladyslav
    @senioroman4uk
    looks like you should look into https://mockk.io/#spy
    mwalkerr
    @mwalkerr

    Hello! I'm getting a "no answer found" exception I can't figure out:

    no answer found for: List(child of #13#14).iterator()
    io.mockk.MockKException: no answer found for: List(child of #13#14).iterator()

    The list object is:

    mockk<SomeDataWrappingClass>().apply {
                        every { data } returns listOf(someDataObject)
                    }
    My expectation is that accessing data just returns the actual list object. It seems like it's instead returning a mockk proxy instead?
    For more context, the code under test is doing:
    wrapperObject.data.find { it.someFlag }
    mwalkerr
    @mwalkerr
    strangely enough the same code works when run on the mocked object inside the test but not when run from the code under test
    mwalkerr
    @mwalkerr
    ah got it! Not sure why it's an issue, but I had
    every { someService.someMethod(wrapperObject.data[0]) } returns someResponse
    and after that, I would get an exception trying to access the data object and use it as a list
    mwalkerr
    @mwalkerr
    Apologies if this is already a documented restriction, but here's a minimal reproducing example:
    class MockkGotchas {
        class DataWrapper {
            val data: List<String> = listOf()
        }
    
        class MockableService {
            fun printString(string: String) {
                TODO()
            }
        }
    
        /**
         * It appears that using a mockk object in an `every` block changes that mockk object. The test below fails
         */
        @Test
        fun using_mockk_object_in_every_block_changes_it() {
            val mockkedService = mockk<MockableService>()
            val mockkedDataWrapper = mockk<DataWrapper>().apply {
                every { data } returns listOf("some string")
            }
            println("the string: ${mockkedDataWrapper.data[0]}")
            every { mockkedService.printString(mockkedDataWrapper.data[0]) } just Runs
            println("the string: ${mockkedDataWrapper.data[0]}")
        }
    }
    Andrea Cisternino
    @acisternino

    Hi all,
    I am trying to mock a class that has no default constructor and that it is provided as a dependecy to another client class.
    When I run the test, it fails when creating the client class.
    Minimal example:

    class SampleService(val arg: String) {
        ....
    }
    
    class SampleServiceClient(val service: SampleService) {
        ....
    }
    
    @ExtendWith(MockKExtension::class)
    internal class ServiceTest {
    
        @MockK lateinit var service: SampleService
    
        @InjectMockKs val sampleServiceClient = SampleServiceClient(service)
    
        @Test
        fun sampleTest() {
            every {
                service.doSomething()
            } returns "value"
            ....
        }
    }

    The error is:

    kotlin.UninitializedPropertyAccessException: lateinit property service has not been initialized
        at pippo.SampleServiceTest.<init>(SampleServiceTest.kt:17)

    What am I doing wrong?

    mwalkerr
    @mwalkerr
    @acisternino don't instantiate SampleServiceClient yourself, just declare it:
    @InjectMockKs val sampleServiceClient: SampleServiceClient
    Doix
    @Doix
    Hey, if I have override fun canSelfDisappear(): Boolean = super.canSelfDisappear() || canWidthDisappear(), can I somehow stub the super.canSelfDisappear() call with mockk? I've been looking through all the docs and can't seem to find anything similar to this.
    Aman Bansal
    @iamanbansal
    object LumosAnalyticsHandler{
    
    fun sendTemplateClickEvent(context: Context, card: Card?, additionalAttributes: HashMap<String, Any>? = null, eventName: String?=null, screenName: String?=null, verticalPos: Int?=null) {
    //
    
    }
    
    @Test
    fun  performClick_sendEvent{
    mockkObject(LumosAnalyticsHandler)
    view.callOnClick()
    verify { LumosAnalyticsHandler.sendTemplateClickEvent(any(), any(), any(), any(), any()) }
    }
    Getting this exception
    io.mockk.MockKException: Failed matching mocking signature for
    
    left matchers: [any(), any(), any(), any(), any()]
    Hey, please help
    MikkelHJuul
    @MikkelHJuul

    Hi, I am trying to upgrade my project dependencies. but mockk keeps giving errors:
    io.mockk.MockKException: no answer found for: List(child of #20#23).isEmpty()
    My mocking is initiated this way:

    open class ContextMockingTest {
    
        var pathParamMap: Map<String, String> = mapOf()
        var queryParamMap: Map<String, List<String>> = mapOf()
        var path: String? = null
        var url: String = "https://example.com/$path"
        var queryString: String? = null
    
        var mockCtx = mockk<io.javalin.http.Context>()
        var qParam = slot<String>()
    
        fun initiateMockContext() {
            every { mockCtx.fullUrl() } returns "$url${queryString?.run {"?$queryString"}}"
            every { mockCtx.matchedPath() } returns path.toString()
            every { mockCtx.pathParamMap() } returns pathParamMap
            every { mockCtx.queryParamMap() } returns queryParamMap
            every { mockCtx.queryParam(capture(qParam)) } answers { queryParamMap[qParam.captured]?.first() }
            every { mockCtx.pathParam(capture(qParam)) } answers { pathParamMap[qParam.captured]!! }
            every { mockCtx.queryString() } returns queryString
        }
    }

    It seems to error when calling ::pathParam(...) when no items are accessible in the pathParamMap

    I upgraded from 1.9.3 to 1.10.0
    I upgraded kotlin from 1.3.50 to .1.3.72

    MikkelHJuul
    @MikkelHJuul
    also it only fails sometimes, and I can't really pinpoint any concurrency codewise (except it's allways the same tests failing)
    MikkelHJuul
    @MikkelHJuul
    it always fails on ctx.queryParam("specificString") so I tried writing the line every { mockCtx.queryParam("specificString") } returns null/""/queryParamMap["specificString"]?.first() I also tried removing the other capture, and the slot<string>. And I tried initiating the mock using mockkClass(Context::class), and changing the mock object from var to val.
    nothing changes the outcome
    greedyjude
    @greedyjude
    Hey how can I mock ByteArrray? I need to change the size return to a constant like 100.
    1 reply
    I got this exception
    
    io.mockk.MockKException: Can't instantiate proxy for class kotlin.ByteArray
    
        at io.mockk.impl.instantiation.JvmMockFactory.newProxy(JvmMockFactory.kt:64)
        at io.mockk.impl.instantiation.AbstractMockFactory.newProxy$default(AbstractMockFactory.kt:29)
        at io.mockk.impl.instantiation.AbstractMockFactory.spyk(AbstractMockFactory.kt:102)
        at com.greedygame.commons.utils.FileUtilsTest.save fails with accepted content length not equal to saved bytes size(FileUtilsTest.kt:248)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        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.InvokeMethod.evaluate(InvokeMethod.java:17)
        at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
        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.junit.runner.JUnitCore.run(JUnitCore.java:137)
        at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
        at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
        at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
        at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
    Caused by: io.mockk.proxy.MockKAgentException: Failed to create proxy for class [B.
    class [B is an array
        at io.mockk.proxy.jvm.ProxyMaker.throwIfNotPossibleToProxy(ProxyMaker.kt:127)
        at io.mockk.proxy.jvm.ProxyMaker.proxy(ProxyMaker.kt:28)
        at io.mockk.impl.instantiation.JvmMockFactory.newProxy(JvmMockFactory.kt:34)
        ... 26 more
    zheng-wang-hexad
    @zheng-wang-hexad
    hi, could some one help me to find the copyright and the vendor of the mockk project?
    stidch
    @stidch
    hi all
    I hope I'm at the right place here to ask the following question.
    In the following code I actually want to test if the observer(Mock) is called twice, once with ServiceState.STARTING and once with ServiceState.RUNNING.
    I have set a breakpoint at observerMock(it) and can see that it's called twice only twice, as expected (1st: STARTING, 2nd: RUNNING).
    Three other breakpoints are at the instruction it == ServiceState.STARTING resp. it == ServiceState.RUNNING. All these three breakpoints are hit, even though the instruction observerMock(it) was hit only twice.
    Is there an obvious explanation, why the second verify matches? I don't get it.
    Every input is welcome. Thank you very much!
    val observerMock = mockk<(ServiceState) -> Unit>(relaxed = true)
    val token = getService().serviceState.register( { observerMock(it) } )
    
    getService().start({result(it)}) { error(it) }
    
    verify(exactly = 1, timeout = TEN_SECONDS) {
        observerMock.invoke(match {it == ServiceState.STARTING })
    }
    verify(exactly = 1, timeout = TEN_SECONDS) {
        observerMock.invoke(match {it == ServiceState.STARTING })
    }
    verify(exactly = 1, timeout = TEN_SECONDS) {
        observerMock.invoke(match {it == ServiceState.RUNNING })
    }
    Pankaj
    @p1729

    hi all
    I am trying to mock OffsetDateTime calls ...but I am getting io.mockk.MockKException: can't find stub OffsetDateTime(temporary mock)

    I am doing these two in my tests

    mockkStatic(OffsetDateTime::class)
    every { OffsetDateTime.now(any<ZoneOffset>()) } answers { OffsetDateTime.parse("2020-08-10T10:00:00Z") }

    I suspect issue using parse() but not sure what is the issue

    MikeDepies
    @MikeDepies
    Hi, I'm getting this error when I build my MultiPlatform project:
    Could not resolve io.mockk:mockk:1.10.0.
    Required by:
        project :
    
    Possible solution:
     - Declare repository providing the artifact, see the documentation at https://docs.gradle.org/current/userguide/declaring_repositories.html
    plugins {
        kotlin("multiplatform") version "1.4.0"
    
    }
    
    group = "me.michael.depies"
    version = "1.0-SNAPSHOT"
    
    repositories {
        mavenCentral()
    }
    dependencies {
        commonTestImplementation("io.mockk:mockk:1.10.0")
    }
    ...
    could anyone help point me in the right direction? I was under the impression that mockK is multi platform.
    Was I mistaken in that mockK is multiPlatform?
    Alexander Jeigalo
    @ajeihala
    Hello. Is there a new mockk release planned? I see there's an important commit that fixes android Robolectric test framework (mockk/mockk@2c3a3c4) and that alone is worth of a new release. Otherwise it blocks upgrading Robolectric.
    afaktor
    @afaktor
    Hi there! Is it possible to use a slot to capture an assignment to a property of a mockked object?
    Wesley Choate
    @wesleychoate
    Hi! Quick question. I know that MockK supports a lot of the things that Mockito supports, and more. Is there any plan to add the "Mockito.CALLS_REAL_METHODS" for testing concrete methods in abstract classes? Just curious. Thanks!
    Alexander Jeigalo
    @ajeihala
    @wesleychoate no idea :) But you can use spyk() for that.
    Wesley Choate
    @wesleychoate
    Ok will try that instead. Thanks!
    Panagiotis Karampis
    @chmod

    Hi! I am experiencing an issue with kotlin 1.4.10 and mockk 1.10.2.
    The same piece of test code works in 1.3 kotlin:

    val configuration = mockkClass(Configuration::class)
            every { configuration.regionId } returns "123"
            val provider = mockkClass(ConfiguratorProvider::class)
            every {
                provider.getConfiguration()
            } returns configuration

    It seems that it actually invokes the getConfiguration() instead of mocking it.

    Panagiotis Karampis
    @chmod
    Update: Kotlin version doesn't make a difference. Some times it works, some times it doesn't. I haven't been able to figure out the behaviour.
    Panagiotis Karampis
    @chmod
    Update: Fixed, there was a name clash, having property configuration and method getConfiguration().
    Noah
    @noahjutz
    Hi,
    I'm getting java.lang.ExceptionInInitializerError [...] caused by io.mockk.proxy.MockKAgentException: Could not set up hiddenApiExemptions, when I try to use mockk for android instrumented tests (using jetpack compose). I can't find anything on this exception, can someone please help me?
    Noah
    @noahjutz
    Never mind. it magically disappeared after doing a bunch of stuff including
    • invalidate caches/restart
    • ./gradlew clean
    • ./gradlew connectedCheck
    David Silva
    @davidafsilva
    Hey everyone,
    Trying mockk for the first time here, have been using mockito-kotlin for quite a while now.
    I'm stubbing, or trying to stub, a call to a mock which one of its parameters is a vararg of Any?. All of the anyVararg or vararg* constructs seem to be bound to non-nullable types (T : Any) . Is there any other construct to capture that parameter? Or perhaps I am doing something wrong.
    Any help will be appreciated, Thanks!
    nick-capsule-glitter
    @nick-capsule-glitter

    Is it possible to callOriginal() within a coEvery?

    When I try I'm seeing Exception in thread "main" kotlinx.coroutines.CoroutinesInternalError: Fatal exception in coroutines machinery for DispatchedContinuation[...] and Caused by: java.lang.ClassCastException: class kotlin.coroutines.intrinsics.CoroutineSingletons cannot be cast to class java.lang.Number

    nick-capsule-glitter
    @nick-capsule-glitter
    A toy example if of interest:
        class TestClass {
            suspend fun testFun(): Int {
                delay(100)
                return 1
            }
        }
    ...
        val spy = spyk(TestClass())
        coEvery { spy.testFun() } answers { callOriginal() }
        runBlocking {
            spy.testFun()
        }