https://kotlinlang.org logo
Join Slack
Powered by
# mockk
  • e

    Endre Deak

    06/03/2024, 2:53 PM
    Hi, I've updated Mockk to the latest, also updated Kotlin to 2.0.0, and now here's my issue:
    Copy code
    interface X<T: Comparable<T>> {
        fun get(): T
    }
    
    @Test
    fun `test x`() {
        val x = mockk<X<Int>>()
        
        every { x.get() } returns 1 # fails
        every { x.get().hint(Int::class) } returns 1 # fails
    
        val result = x.get()
    
        result shouldBe 1
    
        verify(exactly = 1) {
            x.get()
        }
    }
    
    # workaround:
    interface TypedX : X<Int>
    
    @Test
    fun `test x`() {
        val x = mockk<TypedX>()
        
        every { x.get() } returns 1 # passes
    
        val result = x.get()
    
        result shouldBe 1
    
        verify(exactly = 1) {
            x.get()
        }
    }
    The error I get:
    Copy code
    Class cast exception happened.
    Probably type information was erased.
    In this case use `hint` before call to specify exact return type of a method.
    
    io.mockk.MockKException: Class cast exception happened.
    Probably type information was erased.
    In this case use `hint` before call to specify exact return type of a method.
    
    Caused by: java.lang.ClassCastException: class io.mockk.renamed.java.lang.Number$Subclass3 cannot be cast to class java.lang.Comparable (io.mockk.renamed.java.lang.Number$Subclass3 is in unnamed module of loader 'app'; java.lang.Comparable is in module java.base of loader 'bootstrap')
    ...
  • d

    David Kubecka

    06/04/2024, 1:20 PM
    I would like to capture a no-arg lambda argument and then invoke it. The problem is that the return type of the lambda is inferred and differs per each invocation. Is there any way how can I construct a mock for this scenario?
    Copy code
    fun <T> execute(operation: Operation, contract: ContractDTO, block: () -> T): T
    
    every { execute(any(), any(), captureLambda()) } answers {
       lambda<() -> ???>().invoke()
    }
    How to specify the
    lambda
    type so that it can be used for any actual type
    T
    ?
    e
    • 2
    • 2
  • d

    David Kubecka

    06/06/2024, 8:33 AM
    I've run into a funny/strange issue. Not sure it's strongly related to mockk but I've encountered it in that context. I'm using this for comparing recursive structures in tests (using AssertJ):
    Copy code
    fun <T> assertEqualsRecursive(actual: T, expected: T, vararg ignoringFields: String) {
        assertThat(actual)
            .usingRecursiveComparison().withStrictTypeChecking().ignoringFields(*ignoringFields)
            .isEqualTo(expected)
    }
    In my actual test case I'm capturing a list argument into a slot:
    Copy code
    val messageValuesSlot = slot<List<SomeType>>()
    val actualMessages = messageValuesSlot.captured
    and then comparing it with an expected list:
    Copy code
    assertEqualsRecursive(actualMessages, listOf(...))
    The problem is that thanks to the
    withStrictTypeChecking
    option the comparison fails with
    Copy code
    actual and expected are considered different since the comparison enforces strict type check and expected type java.util.Arrays$ArrayList is not a subtype of actual type java.util.ArrayList
    So if I understand it correctly • There are for some reason two
    ArrayList
    in java.util • The
    listOf
    constructor uses different
    ArrayList
    than the mockk when filling the
    messageValuesSlot
    Why is that? Why mockk doesn't use
    listOf
    ? Is there anything I can do about that other than reverse-engineer mockk and use the same
    ArrayList
    ?
    e
    s
    • 3
    • 18
  • l

    Larry Garfield

    07/03/2024, 4:38 PM
    Hi folks. I’m struggling with a mock setup and could use help from someone who has, you know, used Kotlin, Mockk, or Spring Boot before February when I started. 😬 (Details in 🧵 )
    e
    j
    • 3
    • 17
  • k

    Kev

    07/13/2024, 9:16 AM
    Hi. I’m having an issue with mockk/arrow. If my return type is a String, the test passes. If the return type is a value class, I get an error
    Inconsistent number of parameters in the descriptor and Java reflection object: 3 != 2
    . Common code between the tests are:
    Copy code
    data object MyError1
    data object MyError2
    
    @JvmInline
    value class TestId(val id: String)
    Failing code:
    Copy code
    class Foo {
      context(Raise<MyError2>)
      suspend fun foo(): TestId {
        return TestId("hello")
      }
    }
    
    class Service(private val foo: Foo) {
      context(Raise<MyError1>)
      suspend fun test(): TestId {
        return withError({ MyError1 }) {
          foo.foo()
        }
      }
    }
    
    test("test 1") {
          val foo = mockk<Foo>()
          val service = Service(foo)
    
          coEvery {
            with(any<Raise<Any>>()) {
              foo.foo()
            }
          }.coAnswers { TestId("hello") }
    
          either {
            service.test()
          }.shouldBeRight()
        }
    Passing code (where instead of having a
    TestId
    return type, I have a
    String
    return type.
    Copy code
    class Foo {
      context(Raise<MyError2>)
      suspend fun foo(): String {
        return "hello" 
      }
    }
    
    class Service(private val foo: Foo) {
      context(Raise<MyError1>)
      suspend fun test(): String {
        return withError({ MyError1 }) {
          foo.foo()
        }
      }
    }
    
        test("test 1") {
          val foo = mockk<Foo>()
          val service = Service(foo)
    
          coEvery {
            with(any<Raise<Any>>()) {
              foo.foo()
            }
          }.coAnswers { "hello" }
    
          either {
            service.test()
          }.shouldBeRight()
        }
  • d

    Daniele Andreoli

    08/01/2024, 9:13 AM
    Hello, i have a problem with mockin a List of mock. I’m tring to mock this type:
    Copy code
    @MockK
    lateinit var mockAnalyticsReporters: List<AnalyticsReporter?>
    when using this I recieve this strange error:
    class kotlin.Unit cannot be cast to class java.lang.Boolean (kotlin.Unit is in unnamed module of loader 'app'; java.lang.Boolean is in module java.base of loader 'bootstrap')
    java.lang.ClassCastException: class kotlin.Unit cannot be cast to class java.lang.Boolean (kotlin.Unit is in unnamed module of loader 'app'; java.lang.Boolean is in module java.base of loader 'bootstrap')
    at io.mockk.renamed.java.util.Iterator$Subclass5.hasNext(Unknown Source)
    I actually can’t understand what this means. I’m not a very well tester so i need some help. Thanks.
    m
    k
    • 3
    • 14
  • v

    Vaibhav Jaiswal

    09/13/2024, 7:24 AM
    Hey everyone I am facing a weird error when im stubbing a suspend function to return a serialized data My test fails with exception that, it cannot be serialized due to null value This is my stubbing
    Copy code
    val user = User(
        displayName = "",
        contactNumber = "",
        location = null,
        email = "",
        profileImageUrl = "",
        connectionCount = 0,
        followersCount = 0,
        id = "",
        summary = "",
        tagline = "",
        slug = "",
        totalExperienceInMonths = 0,
        createdAt = DateHelpers.now,
        isFollowed = false,
    )
    val resultUser = user.copy(token = Arb.string().
    coEvery {
        apiService.createUser(user, "", "")
    } returns resultUser
    
    //call function to test
    userRepo.createUser(user, "", "")
    Which returns fine, when i debug using breakpoints But the function which I am testing, does this internally
    Copy code
    preferences.user = json.encodeToString(user)
    Which crashes the test, even though the type User is Serializable Stack trace in thread 🧵
    • 1
    • 1
  • c

    Chuong

    10/06/2024, 11:22 PM
    Hi. I have an
    Enum
    class with
    kotlinx-serialization
    .
    Copy code
    @Serializable
    enum class Certificate {
      @SerialName("Certificate_A") A
    }
    For the purposes of testing, I want to add another
    Enum
    entry.
    Copy code
    @SerialName("Certificate_B") B
    How do I do that with
    mockk
    ?
    e
    m
    • 3
    • 4
  • m

    Mattia Tommasone

    10/08/2024, 11:42 AM
    Hey, you know, it’s October…. #C046QQFQV2M 🙄 I just added a new issue that would be fairly easy to work on if anyone’s interested: https://github.com/mockk/mockk/issues/1304 (also there are some issues tagged with #C046QQFQV2M that are generally easier than others)
  • m

    Mattia Tommasone

    10/09/2024, 12:13 PM
    New release! https://github.com/mockk/mockk/releases/tag/1.13.13 🎉 Lots of new contributors, big thanks to @SackCastellon, @Gala Bill, @mgaetan89 and all the others that I wasn’t able to tag :)
    thank you color 1
    🔥 1
    p
    • 2
    • 1
  • v

    Vaibhav Jaiswal

    10/12/2024, 4:26 AM
    Any timeline on when mockK will support KMP?
    m
    j
    • 3
    • 2
  • m

    Marek Kubiczek

    10/16/2024, 1:52 PM
    Is
    mockkStatic
    safe to use with parallel test execution? I mean the Gradle option
    maxParallelForks
    . My understanding is it just spawns multiple jvm processes with their own class loaders. As such static mocks from one process shouldn't leak to the other, correct?. As I understand tests are still run sequentially within each process. In reality though we see test failures that look like they leak happens. We use Junit4 and it's Android project.
    t
    • 2
    • 1
  • d

    David Corrado

    10/31/2024, 4:00 PM
    Got an interesting issue. Apparently roboelectric and mockk do not play well together. Is there any known way to make them work better together. See 🧵
    g
    • 2
    • 10
  • p

    phldavies

    11/26/2024, 10:58 AM
    Is there any likelihood of a patch release containing https://github.com/mockk/mockk/pull/1314 any time soon?
    d
    • 2
    • 1
  • s

    Shubo

    12/16/2024, 5:13 AM
    Could anyone suggest a workaround to this issue? https://github.com/mockk/mockk/issues/1324
  • v

    Vinicius Matheus

    12/16/2024, 1:37 PM
    Is anyone else having issues mocking a
    value class
    return with the 1.13.13 version?
    d
    • 2
    • 3
  • a

    André Martins

    12/20/2024, 3:04 PM
    Hey all, I'm verifying calls to a mocked object and I'm getting
    io.mockk.MockKException: No other calls allowed in stdObjectAnswer than equals/hashCode/toString
    but no clue why this is happening 😓 Has anyone got this exception before? Thanks in advance ✌️
    d
    • 2
    • 1
  • h

    hho

    01/21/2025, 10:17 AM
    Is there any way to get IntelliJ to realize that properties annotated with
    @InjectMockKs
    etc. are not, in fact, unused?
    • 1
    • 2
  • n

    Noah

    01/30/2025, 4:09 PM
    Hello lovely Mockkers! In my test, this line where I mock a return from
    repository
    Copy code
    every { repository.save(any()) } returns fleetEntity
    Returns the following after switching JDK from Eclipse Temurin to docker.io/ibm-semeru-runtimes:open-17.0.13_11-jdk
    Copy code
    FleetServiceTest > should return created fleet given request() FAILED
        io.mockk.MockKException at FleetServiceTest.kt:44
            Caused by: java.lang.ClassCastException at FleetServiceTest.kt:44
    repository interface:
    Copy code
    package org.springframework.data.repository;
    
    import java.util.Optional;
    
    @NoRepositoryBean
    public interface CrudRepository<T, ID> extends Repository<T, ID> {
        <S extends T> S save(S entity);
    
        <S extends T> Iterable<S> saveAll(Iterable<S> entities);
    
        Optional<T> findById(ID id);
    
        boolean existsById(ID id);
    
        Iterable<T> findAll();
    
        Iterable<T> findAllById(Iterable<ID> ids);
    
        long count();
    
        void deleteById(ID id);
    
        void delete(T entity);
    
        void deleteAllById(Iterable<? extends ID> ids);
    
        void deleteAll(Iterable<? extends T> entities);
    
        void deleteAll();
    }
    Any ideas as to why this CastException occurs all of a sudden after changing the JDK? This is important because the new JDK image has a significantly smaller memory footprint.
    d
    e
    • 3
    • 4
  • m

    Michael de Kaste

    02/25/2025, 1:31 PM
    how do I mockk KPropertys from mocked classes?
    Copy code
    class Organisation(
        var name: String,
    )
    
    val organisation = mockk<Organisation>()
    val property: KMutableProperty0<String> = mockk()
    
    every { organisation::name } returns property
    this does not work because the every { ... } call does not contain a mocked call
  • j

    Jacob

    03/03/2025, 1:20 AM
    Did the spring ninja squad mockkbean library move to another maintainer? Is there any changes around it now that old java mockbean has been deprecated in favor of mockitobean?
  • k

    Klitos Kyriacou

    04/15/2025, 3:54 PM
    On the website there is this example:
    Copy code
    every { 
        constructedWith<MockCls>(OfTypeMatcher<String>(String::class)).add(2) // Mocks the constructor which takes a String
    } returns 3
    Why does
    OfTypeMatcher
    need to have the type
    String
    mentioned twice? If it was defined differently, we would be able to have just
    OfTypeMatcher<String>()
    (if we used reified generics), or just
    OfTypeMatcher(String::class)
    . Perhaps I've misunderstood its usage and the two
    String
    type references don't have to be the same?
  • e

    Emre

    04/25/2025, 2:53 AM
    I'm having trouble mocking in the presence of value classes. Invalid arguments that don't exist in my code somehow get passed to the value class' constructor, which fails them. They appear to be caused by reflection in mockk. Does anyone have pointers?
  • m

    Mikolaj

    06/02/2025, 10:37 AM
    Hi! is it possible to mock every function/property that returns a string in class? I have a class where all of methods and properties return string (for string resources) and I want to have something like this:
    Copy code
    private val i18n: I18n = mockk<I18n> {
            every<String> { any() } returns ""
        }
    e
    • 2
    • 1
  • m

    Mattia Tommasone

    06/22/2025, 9:29 PM
    hello channel! I’m migrating the publishing process from OSSRH to Maven Central portal as OSSRH is sunsetting at the end of June. I’m currently publishing v1.14.4 which is identical to v1.14.3 that I published a couple days ago, but with the new publishing process. I’d like to have feedback that the two versions are, indeed, identical and that the new publishing process works correctly 🙂
  • e

    Edgar

    07/01/2025, 11:32 AM
    Hi! I wanted to start using mockk in a KMP project but the IDE is alerting me with this message:
    Cannot access class 'MockKMatcherScope'. Check your module classpath for missing or conflicting dependencies.
    Does anyone have some clue about this? Thank you so much in advance!
  • a

    Arnab

    07/09/2025, 8:36 AM
    Let's say I have a class with some function:
    Copy code
    class Bar {
       fun foo(arg1: String, arg2: String? = null) = "Hello World"
    }
    How can I mock this without providing matchers for all arguments in the function? Essentially I want to do something like this:
    Copy code
    every { barMock.foo } returns "Something Else"
    g
    • 2
    • 2
  • m

    Matteo Mirk

    07/11/2025, 9:22 AM
    Hello, I have a doubt about about thread safety: suppose I'm running the test suite in parallel, so that within the same JVM process test classes are executed by different threads. If a test uses
    clearAllMocks()
    , is it thread-safe? Will it somehow clear only this class/thread mocks or will it bulldoze everything within the same process? Can it affect the behaviour of another test running in parallel?
    e
    • 2
    • 2
  • v

    v79

    07/13/2025, 6:43 PM
    I've been trying to mock a
    java.io.File
    object and it's not going well. I've just seen the documentation that says that this class is restricted by default, and cannot be mocked. I definitely used to be able to... seven years ago! What's the best practice for handling these files in mockk now?
    s
    e
    +2
    • 5
    • 15
  • v

    v79

    07/31/2025, 9:58 PM
    Sorry, me again. Is there any way of listing all the declared mocks? As in, you're convinced that you've set up a mock correctly but
    coVerify
    insists it was not called.
    Copy code
    no answer provided for DynamoDBService(#8).upsertContentNode(eq(domain.com/sources/posts/my-post.md), eq(domain.com), eq(Posts), any(), eq({}), any()))
    And yet...
    Copy code
    declareMock<DynamoDBService> {
                every { mockDynamoDBService.logger = any() } just runs
                every { mockDynamoDBService.logger } returns mockLogger
                coEvery {
                    mockDynamoDBService.upsertContentNode(
                        "domain.com/sources/posts/my-post.md", "domain.com", 
                            SOURCE_TYPE.Posts,
                        any<ContentNode.PostNode>()
                    )
                }
            }
    e
    • 2
    • 9