В моем случае я использовал JUnit 5, поэтому я не смог использовать PowerMock, а Mockito не обеспечивает насмешку статических методов.Я немного переписал свой производственный код, чтобы мне не нужно было имитировать статический метод UUID.
Я использовал интерфейс поставщика
public class TestedClass {
private final Supplier<UUID> uuidSupplier = UUID::randomUUID;
public String getUuid() {
return uuidSupplier.get().toString();
}
}
Затем я использовал отражение, чтобы проверить его
public class TestedClassTest {
@Test
public void testMethod() throws NoSuchFieldException, IllegalAccessException {
Supplier<UUID> uuidSupplier = mock(Supplier.class);
TestedClass testedClass = new TestedClass();
Field uuidSupplierField = TestedClass.class.getDeclaredField("uuidSupplier");
uuidSupplierField.setAccessible(true);
uuidSupplierField.set(testedClass, uuidSupplier);
String uuid = "5211e915-c3e2-4dcb-0776-c7b900f38ab7";
when(uuidSupplier.get()).thenReturn(UUID.fromString(uuid));
assertEquals(uuid, testedClass.getUuid());
}
}
Как рекомендовано автором вопроса, вот мой импорт:
import org.junit.jupiter.api.Test;
import java.lang.reflect.Field;
import java.util.UUID;
import java.util.function.Supplier;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
А здесь мои зависимости:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.2.0</version>
<scope>test</scope>
</dependency>
Надеюсь, это поможет кому-то еще.