Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Activity
    kayFpunkt
    @kayFpunkt

    Hey have a problem by using a foreach loop of an object which is extending a Map. I try to setup my mocking like this

    val tableMock = mockk<MyTable>(relaxed = true, name = "My table Mock")
    val tableEntryMock = mockk<MyEntry>(relaxed = true, name = "My entry Mock")
    every { tableMock[any()] } returns tableEntryMock

    But in my foreach, where I'm iteration over MyTable nothing happen because its size is 0, obviously. So I try:

    val tableMock = mockk<MyTable>(relaxed = true, name = "My table Mock")
    val tableEntryMock = mockk<MyEntry>(relaxed = true, name = "My entry Mock")
    val expectedMap = mutableMapOf<Int, MyEntry>(1 to tableEntryMock)
    every { tableMock.iterator() } answers expectedMap.iterator()

    But the precompiler has a problem with my 'answers' :
    None of the following functions can be called with the arguments supplied. answers(Answer<MutableIterator<MutableMap.MutableEntry<Int, MyTable>>>) defined in io.mockk.MockKStubScope answers(MockKAnswerScope<MutableIterator<MutableMap.MutableEntry<Int, MyTable>>, MutableIterator<MutableMap.MutableEntry<Int, MyTable>>>.(Call) → MutableIterator<MutableMap.MutableEntry<Int, MyTable>>) defined in io.mockk.MockKStubScope

    Mattia Tommasone
    @Raibaz

    answers takes a block, not a value
    you should be doing

    every { tableMock.iterator() } returns expectedMap.iterator()

    or

    every { tableMock.iterator() } answers { expectedMap.iterator() }
    kayFpunkt
    @kayFpunkt

    answers takes a block, not a value
    you should be doing

    every { tableMock.iterator() } returns expectedMap.iterator()

    or

    every { tableMock.iterator() } answers { expectedMap.iterator() }

    Thanks to @Raibaz this doesn't solves the problem fully, but brings me one step forward (was using 'answers' wrong). Problem is a different type of the Iterators.

    Anna J McDougall
    @AJMcDee
    Hi friendos...
    I'm trying to verify that a call was made. I'm using verify (exactly =1) and there's no problem when passing in a normal string as an argument, but it's saying was not called when I use a list of strings as an argument. I've tried every combination of eq and similar that I can think of, but it's still insisting that the function hasn't been called when it definitely has. I thought it could be a reference vs value thing, but the eq thing negates that as an option. Any ideas?
    Mattia Tommasone
    @Raibaz
    can you please paste the two verify blocks you’re using, the one with the normal string and the one with the list of strings?
    Anna J McDougall
    @AJMcDee
    image.png
    Sorry I'm working on a virtual machine so only have screenshots
    image.png
    My two mocked calls:
    Both are necessary to get the correct results back, and the results coming back are correct, so it must be being called but still comes back as was not called.
    Mattia Tommasone
    @Raibaz
    can you try verifying the second function with any() rather than buildingIdList.buildingIds?
    Anna J McDougall
    @AJMcDee
    OK
    That's failing too! Guess it's not a list problem, then.
    Mattia Tommasone
    @Raibaz
    yep
    Anna J McDougall
    @AJMcDee
    OK I tried commenting out the repositoryMock call and it still works. Thanks for your help, I'll look into it some more!
    Mattia Tommasone
    @Raibaz
    np :)
    xaderfos
    @xaderfos
    Hello, has anyone tried to mock the Sentry Java class? It is a final class and I'm trying to verify the call of one of its static methods. I've searched every bit of the documentation and SO but can't figure it out. At best I got a io.mockk.MockKException: Missing calls inside verify { ... } block.
    xaderfos
    @xaderfos
    To answer my own question... mockk/mockk#121
    Mattia Tommasone
    @Raibaz
    i think you should call mockkObject on the companion object
    something like mockkObject(SampleTest.companion)
    xaderfos
    @xaderfos

    To answer my own question... mockk/mockk#121

    Aaah wrong chat, please ignore this one

    ketanMuttha
    @ketanMuttha
    @Raibaz you are right. I fixed using the same.mockkObject(SampleTest)
    Thanks
    Mattia Tommasone
    @Raibaz
    cool, happy to help :)
    Coderx64
    @Coderx64

    Hi guys, i'm trying to deal with chained calls verify, but it's not work :(
    here is my example, could you pls take a look? (sorry for bad english)

    @Test
        fun testChainedCallVerify() {
            val mock = mockk<RedisTemplate<String, String>>() {
                every { boundValueOps(match { it.startsWith("sys_") }) } returns mockk() {
                    every { get() } returns "0"
                }
                every { boundValueOps(match { it.startsWith("aux_") }) } returns mockk() {
                    every { get() } returns System.currentTimeMillis().toString()
                }
            }
    
            println(mock.boundValueOps("sys_1").get())
            println(mock.boundValueOps("aux_2").get())
    
            verify { mock.boundValueOps(eq("sys_1")).get() } //without get() this verify doesnt fails
            verify { mock.boundValueOps(eq("aux_2")).get() } //without get() this verify doesnt fails
    
            /*val boundOpsMock = mock.boundValueOps("sys_1")
            verify { boundOpsMock.get() } //but it's work, except confirmVerified*/
    
            confirmVerified(mock)
        }

    and i getting exception java.lang.AssertionError: Verification failed: call 2 of 2: BoundValueOperations(child of #19#23).get()) was not called

    Augier
    @augierle42e:matrix.org
    [m]
    Hello! I have a problem with Mockk. I'm not yet sure this is a bug or not. I have an Android app where I'm testing a lambda passed to an object is correctly called by passing a Mockk spy. But I get an io.mockk.MockKException: Missing calls inside verify { ... } block error on Android API level 21 where the test passes correctly on Android API level 30. Error is reproduced both on my Jenkins CI and my computer.
    2 replies
    Darshan Mistry
    @mistrydarshan99
    Any github repo in which mockk used for mocking object in Android UI testing?
    Darshan Mistry
    @mistrydarshan99
    MockkAnnotations.init(this) is not working in Android UI test
    1 reply
    any workaround for this
    JohnnyV
    @JohnnyV

    Hi everyone, I am struggling with testing objects implementing abstract classes:

    abstract class Base(open val lib: Lib) {
        abstract fun Lib.doTheThing()
    
        fun meaningfulStep() = lib.doTheThing()
    }
    
    class SomeImpl(lib: Lib) : Base(lib = lib) {
        override fun Lib.doTheThing() {
            lib.doSomeThing()
        }
    }
    
    class AnotherImpl(lib: Lib) : Base(lib = lib) {
        override fun Lib.doTheThing() = lib.doAnotherThing()
    }
    
    class Lib {
        fun doSomeThing() = println("I just executed some awesome thing!")
        fun doAnotherThing() = println("I just executed another awesome thing!")
    }

    This is how I would use this example in runtime and it works as expected:

    val lib = Lib()
    
    SomeImpl(lib).meaningfulStep()
    AnotherImpl(lib).meaningfulStep()

    But tests are failing:

        @Test
        fun calling_some_thing() {
            // given
            val mockLib = mockk<Lib>()
    
            val impl = spyk(SomeImpl(mockLib))
    
            // when
            impl.meaningfulStep()
    
            // then
            verify {
                mockLib.doSomeThing()
            }
        }
    
        @Test
        fun calling_another_thing() {
            // given
            val mockLib = mockk<Lib>()
            val impl = spyk(AnotherImpl(mockLib))
    
            // when
            impl.meaningfulStep()
    
            // then
            verify {
                mockLib.doAnotherThing()
            }
        }
    3 replies
    Any idea about what might be wrong?
    Rafhaan Shah
    @RafhaanShah

    How do we set mock responses for Function literals with receiver?

    Basic example:

    interface ThingDoer {
        fun doThing(): String
    }
    
    class DoerProxy {
        private val doer = object : ThingDoer {
            override fun doThing(): String {
                return "did a thing"
            }
        }
    
        fun <T> doProxyThing(func: ThingDoer.() -> T): T {
            return func(doer)
        }
    }
    
    class DoerUser(private val proxy: DoerProxy) {
        fun useThing(): String {
            return proxy.doProxyThing { this.doThing() }
        }
    }
    
    class DoerUserTest {
        @Test
        fun testUseThing() {
            val expected = "something"
            val mockProxy: DoerProxy = mockk()
            every { mockProxy.doProxyThing { doThing() } } returns expected
    
            val doerUser = DoerUser(mockProxy)
            val actual = doerUser.useThing()
            assertEquals(expected, actual)
        }
    }

    Gets me an error: io.mockk.MockKException: no answer found for: DoerProxy(#1).doProxyThing(lambda {})

    4 replies
    Fabio 'MrWHO' Torchetti
    @Wedjaa
    Has anyone figured out a workaround for mockk/mockk#607
    8 replies
    Vladyslav
    @senioroman4uk
    Can someone please review mockk/mockk#676
    DiCaius
    @DiCaius

    Hello, I'm having some trouble mocking a constructor, I'm not even sure if this is possible but I was hoping to get something like this going

    class Foo(val foo: Int) {}
    
    class FooTest {
        @MockK
        lateinit var foo: Foo
    
        @BeforeTest
        fun setup() {
            MockKAnnotations.init(this)
    
            mockkConstructor(Foo::class)
        }
    
        @Test
        fun fooTest {
            every { Foo(any()) } returns this.foo
    
            Foo(0)
    
            verify { Foo(withArgs { assertEquals(it, 0) }) }
        }
    }

    Do you guys have any idea how I could get this behaviour? Thanks in advance.

    Gopalkrishna Mudaliar
    @gopalmudaliar
    Hi am new writing tests i have a very simple test but its failing, would appreciate if some one for guide me what i am doing wrong
    4 replies

    Here is my code @Test funtest 1`() {

        var mockCar = mockk<Car>()
    
        every { mockCar.changState(any()) } just runs
        every { mockCar.setState(any()) } just runs
    
        mockCar.changState(10)
        verify(exactly = 1) { mockCar.changState(any()) }
        verify { mockCar.setState(any()) }

    `

    Getting this error
    java.lang.AssertionError: Verification failed: call 1 of 1: Car(#2).setState(any())) was not called.
    
    Calls to same mock:
    1) Car(#2).changState(10)
    Here is my Car class
    `
    class State {
        var state: Int = 10
    }
    
    class Car {
        //var state:State = State()
        fun changState(data: Int = 1) {
             setState(data)
        }
        fun setState(data: Int = 0) {
            //state.state = data
        }
    }
    Bhargav Suthar
    @SutharBhargav
    Does any one have idea, how to set private value for any collection object?
    Bhargav Suthar
    @SutharBhargav

    Does any one have idea, how to set private value for any collection object?

    class CustInfo {

     private var customerInfoList: MutableList<CustomerInfo> = mutableListOf()
    
      fun updateCustomerInfoList(list: MutableList<CustomerInfo>){
              customerInfoList = list
      }
    
       fun clearItems() {
               if(customerInfoList.isEmpty()){
                    customerInfoList.clear()
                }
        }

    }

    Bhargav Suthar
    @SutharBhargav

    Does any one have idea, how to set private value for any collection object?

    class CustInfo {

     private var customerInfoList: MutableList<CustomerInfo> = mutableListOf()
    
      fun updateCustomerInfoList(list: MutableList<CustomerInfo>){
              customerInfoList = list
      }
    
       fun clearItems() {
               if(customerInfoList.isEmpty()){
                    customerInfoList.clear()
                }
        }

    }

    I am trying to write test case for clearItems() method where I need to update the value for customerInforList private variable

    Ravi medar
    @ravimedar:matrix.org
    [m]
    Hey folks , how can i mock this BuildConfig.BUILD_TYPE
    1 reply
    using Mockk
    any example
    srinivas175
    @srinivas175
    Hey folks, do we have any similar method like suppress in powerMock
    1 reply
    Rafhaan Shah
    @RafhaanShah
    Any equivalent for mockito's InvocationListener to verify some behaviour on every call to a mocked object?
    Alexey Homa
    @sasfmlzr

    Hello! I have a problem with kotlin 1.5.21, 1.5.30, and mocking observers from android lifecycle 2.3.1 with mockk.
    It works on kotlin 1.4.32

    How to reproduce:
    val dialogObserver: Observer<Unit> = mockk() every { dialogObserver.onChanged(any()) }.returns(Unit)

    Log:
    Failed matching mocking signature for SignedCall(retValue=java.lang.Void@91af3b8, isRetValueMock=false, retType=class java.lang.Void, self=Observer(#6), method=onChanged(Any), args=[kotlin.Unit], invocationStr=Observer(#6).onChanged(kotlin.Unit)) left matchers: [any()] io.mockk.MockKException: Failed matching mocking signature for SignedCall(retValue=java.lang.Void@91af3b8, isRetValueMock=false, retType=class java.lang.Void, self=Observer(#6), method=onChanged(Any), args=[kotlin.Unit], invocationStr=Observer(#6).onChanged(kotlin.Unit)) left matchers: [any()]

    2 replies
    Simone D'Avico
    @simonedavico
    Hi everyone! I have a basic project set up with http4k and gradle and I'm using mockk in my tests. The tests run fine, but when I open my project with IntelliJ IDEA it complains that it cannot access class io.mockk.Ordering. Running the gradle wrapper from terminal works fine, tests run and are green. Tried invalidating caches/restarting IDEA/restarting gradle daemon multiple times, nothing seems to work. Any clue as to where I may look at next?