Affects: Spring Boot 3.2.2, spring-test 6.1.3
Below is a cut down example showing the issue:
package com.example.demo;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
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)
class DemoApplicationTests {
private static final UUID uuid = UUID.randomUUID();
@Mock
private MockedStatic<UUID> mockedStatic;
@Nested
class nested {
@ParameterizedTest
@ValueSource(ints = { 1, 2 })
void shouldReturnConstantValue(int run) {
mockedStatic.when(UUID::randomUUID).thenReturn(uuid);
UUID result = UUID.randomUUID();
assertThat(result).isEqualTo(uuid);
}
}
}
The problem is that the second time the test runs, the MockedStatic
is not properly closed, and there's an initialisation error when creating the MockedStatic the second time:
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
If the MockedStatic
is moved into the inner class, it works fine, but in the real test I'm working on, I don't want to structure it like that.
It is an inconsistency between the SpringExtension
and the MockitoExtension
. If you comment the SpringExtension
line, and uncomment the MockitoExtension
, then the test works fine.
Comment From: bernie-schelberg-invicara
I'll just add: the issue is not related to the @ParameterizedTest
. That was just a more concise way to demonstrate the issue. The issue also occurs with two separate tests in the nested class.
Comment From: bernie-schelberg-invicara
My mistake, it's a Spring Boot issue, not Spring Framework. I've moved the issue to the spring-boot project: https://github.com/spring-projects/spring-boot/issues/39270