0

I am getting below error when I am using Java 19. I tried using --add-opens=java.base/java.util.concurrent=ALL-UNNAMED, but that also does not help to resolve below issue. How can I mock ThreadLocalRandom when using Java 19? I am not getting any error if I use Java 17 or below version. Below is the code that generates this error.

final ThreadLocalRandom random = Mockito.mock(ThreadLocalRandom.class);
Mockito.when(random.nextInt(Mockito.anyInt())).thenReturn(0);

[ERROR] Failures: [ERROR] Mockito
Cannot mock/spy class java.util.concurrent.ThreadLocalRandom Mockito cannot mock/spy following:

final classes anonymous classes primitive types

I tried --add-opens=java.base/java.util.concurrent=ALL-UNNAMED. I am expecting it should work as it was working in Java 17.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
sKarwasra
  • 45
  • 2
  • ThreadLocalRandom is a final class in jdk19+, I can imagine the class not being final in lower versions. It's not possible to bypass this without changing the java standard library, as far as I know. – 0x150 Apr 25 '23 at 06:54
  • Why are you wanting to mock a library class in the first place? – ndc85430 Apr 25 '23 at 08:43
  • Library class is already mocked a long time back by some one in some unit tests, i am upgrading the jdk version. – sKarwasra Apr 25 '23 at 10:36
  • I am afraind there is no simple fix. If you want to still upgrade the Java version you will need to share here the code of you service in which this "random" is being used. We might propose a workaround solution, which will involve change of implementation of the service and the tests code. – fascynacja Apr 26 '23 at 10:05
  • `ThreadLocalRandom` extends the base class `Random`. It should be possible to mock `Random` (and your code shouldn't care whether it gets a `Random` or a `ThreadLocalRandom` – LSP) – knittl May 01 '23 at 16:42
  • I did tried to use Random but then i encountered below error.java.lang.reflect.InaccessibleObjectException: Unable to make private java.util.Random(java.lang.Void) accessible: module java.base does not "opens java.util" to unnamed module @2957fcb0 at java.base/java.lang.reflect.AccessibleObject.throwInaccessibleObjectException(AccessibleObject.java:387) – sKarwasra May 15 '23 at 09:53

0 Answers0