Skip to content

Mockito's MockedStatic isn't closed in all cases #39271

Closed
@bernie-schelberg-invicara

Description

Possibly related to #39270, there is also an issue when a test in a class is disabled. Example:

package com.example.demo;

import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import java.util.UUID;

import static org.assertj.core.api.Assertions.assertThat;

//@ExtendWith(MockitoExtension.class)
@ExtendWith(SpringExtension.class)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class MultipleTestsNotNestedTests {

	private static final UUID uuid = UUID.randomUUID();

	@Mock
	private MockedStatic<UUID> mockedStatic;

	@Test
	@Order(1)
	@Disabled
	void shouldReturnConstantValueDisabled() {
		mockedStatic.when(UUID::randomUUID).thenReturn(uuid);

		UUID result = UUID.randomUUID();

		assertThat(result).isEqualTo(uuid);
	}

	@Test
	@Order(2)
	void shouldReturnConstantValue() {
		mockedStatic.when(UUID::randomUUID).thenReturn(uuid);

		UUID result = UUID.randomUUID();

		assertThat(result).isEqualTo(uuid);
	}
}

Order is important, the @Disabled test must run (or be skipped) before, not after the other test. When preparing the test instance the second time, the MockedStatic from the first run has not been closed, and the test fails with:

org.mockito.exceptions.base.MockitoException: 
For java.util.UUID, static mocking is already registered in the current thread

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

Removing the @Disabled annotation results in the test passing. Again, using the MockitoExtension instead of the SpringExtension also results in the test working as expected with the @Disabled test.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions