mockk/mockk

mockkStatic is not getting unmocked/cleared correctly

Open

#797 opened on Mar 11, 2022

View on GitHub
 (5 comments) (1 reaction) (0 assignees)Kotlin (364 forks)batch import
bughacktoberfest

Repository metrics

Stars
 (5,540 stars)
PR merge metrics
 (Avg merge 4d 7h) (7 merged PRs in 30d)

Description

Prerequisites

  • I am running the latest version
  • I checked the documentation and found no answer
  • I checked to make sure that this issue has not already been filed

Expected Behavior

After unmocking, I would expect that the SecurityContextHolder is back in its normal operation mode.

Current Behavior

When executing anything on SecurityContextHolder like getContext() after unmocking, a NullPointerException is thrown, as the internal strategy field is not initialized.

Failure Information (for bugs)

Steps to Reproduce

  1. You need the dependency for the spring class SecurityContextHolder
  2. Write a Junit5 test like below
  3. Execute it and you will get the NPE

Context

  • MockK version: 1.12.3
  • OS: Windows 10
  • Kotlin version: 1.6.10
  • JDK version: 11-temurin
  • JUnit version: 5.8.2
  • Type of test: unit test

Minimal reproducible code

import io.mockk.clearAllMocks
import io.mockk.every
import io.mockk.just
import io.mockk.mockkStatic
import io.mockk.runs
import org.junit.jupiter.api.Test
import org.springframework.security.core.context.SecurityContextHolder

class MyTest {
    @Test
    fun test() {
        // Mock
        mockkStatic(SecurityContextHolder::class) // when replaced with mockkStatic(SecurityContextHolder::class.qualifiedName!!), everything works
        every { SecurityContextHolder.clearContext() } just runs  // without this line, everything works

        // Unmock
        clearAllMocks()

        // Try to get SecurityContext -> throws NPE, but should not
        SecurityContextHolder.getContext()
    }
}

Contributor guide