Skip to content

mock(SecureRandom.class) and mock(Random.class) fails #2560

@Kurru

Description

@Kurru

Trying to mock SecureRandom or Random throws exception.

mock(SecureRandom.class);

Throws exception:

Mockito cannot mock this class: class java.security.SecureRandom.

Mockito can only mock non-private & non-final classes.
If you're not sure why you're getting this error, please report to the mailing list.


Java               : 17
JVM vendor name    : Oracle Corporation
JVM vendor version : 17.0.2+8-86
JVM name           : OpenJDK 64-Bit Server VM
JVM version        : 17.0.2+8-86
JVM info           : mixed mode, sharing
OS name            : Mac OS X
OS version         : 12.1


Underlying exception : java.lang.IllegalStateException: Cannot access annotation property public abstract java.lang.String jdk.internal.util.random.RandomSupport$RandomGeneratorProperties.name()
org.mockito.exceptions.base.MockitoException: 
Mockito cannot mock this class: class java.security.SecureRandom.

Mockito can only mock non-private & non-final classes.
If you're not sure why you're getting this error, please report to the mailing list.


Java               : 17
JVM vendor name    : Oracle Corporation
JVM vendor version : 17.0.2+8-86
JVM name           : OpenJDK 64-Bit Server VM
JVM version        : 17.0.2+8-86
JVM info           : mixed mode, sharing
OS name            : Mac OS X
OS version         : 12.1

However, if I disable the annotation mocking, this code completes successfully.

mock(SecureRandom.class, withSettings().withoutAnnotations());

Random and SecureRandom seem relatively common, perhaps this can be handled more gracefully? Or perhaps the error message can highlight that this may be an annotation only problem and thus can be worked around?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions