Skip to content

Mockito Error – To create a new mock, the existing static mock registration must be deregistered

Issue –

static mocking is already registered in the current thread

To create a new mock, the existing static mock registration must be deregistered

Suppressed: java.lang.NullPointerException: Cannot invoke method close() on null object
    at org.codehaus.groovy.runtime.NullObject.invokeMethod(
    at org.codehaus.groovy.vmplugin.v8.IndyGuardsFiltersAndSignatures.invokeGroovyObjectInvoker(
    at org.codehaus.groovy.vmplugin.v8.IndyInterface.fromCache(
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(
    at java.base/java.lang.reflect.Method.invoke(
    at org.spockframework.util.ReflectionUtil.invokeMethod(
    at org.spockframework.runtime.model.MethodInfo.lambda$new$0(
    at org.spockframework.runtime.model.MethodInfo.invoke(
    at org.spockframework.runtime.PlatformSpecRunner.invokeRaw(
    at org.spockframework.runtime.PlatformSpecRunner.invoke(
    at org.spockframework.runtime.PlatformSpecRunner.runFeatureMethod(
    at org.spockframework.runtime.IterationNode.execute(
    at org.spockframework.runtime.SimpleFeatureNode.execute(

Environment –

  • Mockito 3.4.0 or higher
  • Junit 4 or higher
  • Java 8 or higher
  • Groovy 3 or higher

Root cause –

Mockito versions 3.4.0 or higher have introduced mockito-inline for mocking static methods instead of PowerMockito.

Refer to FixMyDev Blog – Mock static methods in Junit 5 in Java and Spock framework

So, it is mandatory to deregister every static mock object after use in a method, so that next test case method can register it again otherwise it will throw static mocking is already registered in the current thread, to create a new mock, the existing static mock registration must be deregistered.

Solution #1 –

For Groovy Spock framework use below solution.

Set mySet = new LinkedHashSet<>()
var mockedStatic = mockStatic(StaticMethodClass.class)
mockedStatic.when({ -> StaticMethodClass.getMySet() }).thenReturn(mySet)


1 * testClass.getTestMethod()


Solution #2 –

For Java Junit framework use below solution.

try (MockedStatic mocked = Mockito.mockStatic(StaticMethodClass.class)) {
mocked.when(() -> StaticMethodClass::getMySet()).thenReturn(mySet);

Do you have another solution?

The solution provided above is based on the scenario our one of the developers/contributors faced. If you faced the same issue and found any other root cause then please share your solution in the comment section below. We will add the solution in this article.

Leave a Reply

Your email address will not be published. Required fields are marked *