mockk icon indicating copy to clipboard operation
mockk copied to clipboard

Mockk eats memory until it crashes if mocked Exception "escapes"

Open gertjanschouten opened this issue 1 year ago • 0 comments

Behavior

If a function is mocked so that it throws an Exception when it runs, and you don't catch this Exception, it will "escape" the function and make your test fail. This is expected.

However, certain Exception types have a lot of fields and instantiating such an Exception (so that you can have the mocked function throw it), is a lot of work.

In such a case, we can mock the Exception itself and throw the mocked Exception.

The expected behaviour is that then too, the test will fail if this mocked Exception "escapes" the function. In reality, mockk will eat your memory until the test runner (maven, intellij, ...) crashes.

Steps to Reproduce

This is actually an issue where the code example below is much easier to understand than the above explanation :)

Context

Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions.

  • MockK version: 1.13.12
  • OS: Ubuntu 22.04.4 LTS / Kernel 5.15.0-117-generic
  • Kotlin version: 2.0
  • JDK version: 21
  • JUnit version: 5.10.3
  • Type of test: unit test

Minimal reproducible code (the gist of this issue)

package io.mockk.gh

import io.mockk.every
import io.mockk.mockk
import org.junit.jupiter.api.Test

class ExceptionTest {

  @Test
  fun testSomeFunction() {
    val someClass = mockk<SomeClass>()

    // every { someClass.someFunction() } throws RuntimeException() //If you uncomment this line and comment the one below, the test will fail as expected
    every { someClass.someFunction() } throws mockk<RuntimeException>(relaxed = true) //If you uncomment this line and comment the one above, the test will eat up all your memory

    someClass.someFunction()
  }
}

class SomeClass {
  fun someFunction() {}
}

gertjanschouten avatar Aug 02 '24 08:08 gertjanschouten