Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could not find sun.misc.Unsafe when I tested model using mockito

I tried to make a mock tests for testing my entity, but I can't run it with java 13 or 11 only java 8. When I used java 8, everything works perfectly and when I change to java 11 or 13 it gives init error

I find some posts on the StackOverflow but Nothing works. I tried to change my dependency of Mockito version, but all the versions give exactly the same problem. I used Evosuite to generate some of the tests.And I don't think that any connects with these problems

mock(Class.forName("java.util.Date", false, Reservation_ESTest_scaffolding.class.getClassLoader()));

then I got this error

    Mockito cannot mock this class: class java.util.Date.

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               : 13
JVM vendor name    : Oracle Corporation
JVM vendor version : 13.0.2+8
JVM name           : Java HotSpot(TM) 64-Bit Server VM
JVM version        : 13.0.2+8
JVM info           : mixed mode, sharing
OS name            : Mac OS X
OS version         : 10.15.3


Underlying exception : java.lang.UnsupportedOperationException: Cannot define class using reflection
org.evosuite.shaded.org.mockito.exceptions.base.MockitoException: 
Mockito cannot mock this class: class java.util.Date.

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               : 13
JVM vendor name    : Oracle Corporation
JVM vendor version : 13.0.2+8
JVM name           : Java HotSpot(TM) 64-Bit Server VM
JVM version        : 13.0.2+8
JVM info           : mixed mode, sharing
OS name            : Mac OS X
OS version         : 10.15.3


Underlying exception : java.lang.UnsupportedOperationException: Cannot define class using reflection
    at nl.tudelft.oopp.group43.project.models.Reservation_ESTest_scaffolding.initMocksToAvoidTimeoutsInTheTests(Reservation_ESTest_scaffolding.java:109)
    at nl.tudelft.oopp.group43.project.models.Reservation_ESTest_scaffolding.initEvoSuiteFramework(Reservation_ESTest_scaffolding.java:44)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
    at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:40)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
    at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)
    at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
    at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:80)
    at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:71)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:220)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:188)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:202)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:181)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:102)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:82)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:78)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at com.sun.proxy.$Proxy2.stop(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.stop(TestWorker.java:132)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:175)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:157)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:404)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.base/java.lang.Thread.run(Thread.java:830)
Caused by: java.lang.UnsupportedOperationException: Cannot define class using reflection
    at org.evosuite.shaded.net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection$Dispatcher$Unavailable.defineClass(ClassInjector.java:821)
    at org.evosuite.shaded.net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection.inject(ClassInjector.java:185)
    at org.evosuite.shaded.net.bytebuddy.dynamic.loading.ClassLoadingStrategy$Default$InjectionDispatcher.load(ClassLoadingStrategy.java:187)
    at org.evosuite.shaded.net.bytebuddy.dynamic.TypeResolutionStrategy$Passive.initialize(TypeResolutionStrategy.java:79)
    at org.evosuite.shaded.net.bytebuddy.dynamic.DynamicType$Default$Unloaded.load(DynamicType.java:4456)
    at org.evosuite.shaded.org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:121)
    at org.evosuite.shaded.org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)
    at org.evosuite.shaded.org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)
    at org.evosuite.shaded.net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:138)
    at org.evosuite.shaded.net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:346)
    at org.evosuite.shaded.net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:161)
    at org.evosuite.shaded.net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:355)
    at org.evosuite.shaded.org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)
    at org.evosuite.shaded.org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:71)
    at org.evosuite.shaded.org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:42)
    at org.evosuite.shaded.org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.createMock(ByteBuddyMockMaker.java:25)
    at org.evosuite.shaded.org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)
    at org.evosuite.shaded.org.mockito.internal.MockitoCore.mock(MockitoCore.java:65)
    at org.evosuite.shaded.org.mockito.Mockito.mock(Mockito.java:1864)
    at org.evosuite.shaded.org.mockito.Mockito.mock(Mockito.java:1777)
    ... 64 more
Caused by: java.lang.IllegalStateException: Could not find sun.misc.Unsafe
    at org.evosuite.shaded.net.bytebuddy.dynamic.loading.ClassInjector$UsingUnsafe$Dispatcher$Disabled.initialize(ClassInjector.java:1357)
    at org.evosuite.shaded.net.bytebuddy.dynamic.loading.ClassInjector$UsingUnsafe.inject(ClassInjector.java:1193)
    at org.evosuite.shaded.net.bytebuddy.dynamic.loading.ClassLoadingStrategy$ForUnsafeInjection.load(ClassLoadingStrategy.java:458)
    at org.evosuite.shaded.net.bytebuddy.dynamic.TypeResolutionStrategy$Passive.initialize(TypeResolutionStrategy.java:79)
    at org.evosuite.shaded.net.bytebuddy.dynamic.DynamicType$Default$Unloaded.load(DynamicType.java:4456)
    at org.evosuite.shaded.net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection$Dispatcher$Indirect.make(ClassInjector.java:684)
    at org.evosuite.shaded.net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection$Dispatcher$CreationAction.run(ClassInjector.java:302)
    at org.evosuite.shaded.net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection$Dispatcher$CreationAction.run(ClassInjector.java:290)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:312)
    at org.evosuite.shaded.net.bytebuddy.dynamic.loading.ClassInjector$UsingReflection.<clinit>(ClassInjector.java:70)
    at org.evosuite.shaded.net.bytebuddy.dynamic.loading.ClassLoadingStrategy$Default$InjectionDispatcher.load(ClassLoadingStrategy.java:184)
    at org.evosuite.shaded.net.bytebuddy.dynamic.TypeResolutionStrategy$Passive.initialize(TypeResolutionStrategy.java:79)
    at org.evosuite.shaded.net.bytebuddy.dynamic.DynamicType$Default$Unloaded.load(DynamicType.java:4456)
    at org.evosuite.shaded.org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:121)
    at org.evosuite.shaded.org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)
    at org.evosuite.shaded.org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)
    at org.evosuite.shaded.net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:138)
    at org.evosuite.shaded.net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:346)
    at org.evosuite.shaded.net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:161)
    at org.evosuite.shaded.net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:355)
    at org.evosuite.shaded.org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)
    at org.evosuite.shaded.org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:71)
    at org.evosuite.shaded.org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:42)
    at org.evosuite.shaded.org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.createMock(ByteBuddyMockMaker.java:25)
    at org.evosuite.shaded.org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)
    at org.evosuite.shaded.org.mockito.internal.MockitoCore.mock(MockitoCore.java:65)
    at org.evosuite.shaded.org.mockito.Mockito.mock(Mockito.java:1864)
    at org.evosuite.shaded.org.mockito.Mockito.mock(Mockito.java:1777)
    at nl.tudelft.oopp.group43.project.validator.UserValidator_ESTest_scaffolding.initMocksToAvoidTimeoutsInTheTests(UserValidator_ESTest_scaffolding.java:113)
    at nl.tudelft.oopp.group43.project.validator.UserValidator_ESTest_scaffolding.initEvoSuiteFramework(UserValidator_ESTest_scaffolding.java:44)
    ... 62 more
Caused by: java.lang.NoSuchMethodException: sun.misc.Unsafe.defineClass(java.lang.String,[B,int,int,java.lang.ClassLoader,java.security.ProtectionDomain)
    at java.base/java.lang.Class.getMethod(Class.java:2109)
    at org.evosuite.shaded.net.bytebuddy.dynamic.loading.ClassInjector$UsingUnsafe$Dispatcher$CreationAction.run(ClassInjector.java:1260)
    at org.evosuite.shaded.net.bytebuddy.dynamic.loading.ClassInjector$UsingUnsafe$Dispatcher$CreationAction.run(ClassInjector.java:1248)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:312)
    at org.evosuite.shaded.net.bytebuddy.dynamic.loading.ClassInjector$UsingUnsafe.<clinit>(ClassInjector.java:1127)
    ... 90 more

my gradle.build is

    plugins {
    id 'org.springframework.boot' version '2.2.4.RELEASE'
    id 'io.spring.dependency-management' version '1.0.9.RELEASE'
    id 'org.asciidoctor.convert' version '1.5.8'
    id 'java'
    id 'application'

}
apply plugin: 'checkstyle'

mainClassName='nl.tudelft.oopp.group43.project.Application'
group = 'nl.tudelft.oopp.group43'
version = '0.0.1'
sourceCompatibility = '8'
configurations {
    developmentOnly
    runtimeClasspath {
        extendsFrom developmentOnly
    }
}

repositories {
    mavenCentral()
    maven {
        url "http://www.evosuite.org/m2"
    }
}

ext {
    set('snippetsDir', file("build/generated-snippets"))
}

checkstyle {
    toolVersion "8.25"
    configFile = rootProject.file('config/checkstyle/checkstyle.xml')

    ignoreFailures = false
    maxErrors = 0
    maxWarnings = 0
}

dependencies {
    implementation "com.google.guava:guava:28.2-jre"
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    compile group: 'org.springframework.security', name: 'spring-security-core', version: '5.2.2.RELEASE'
    implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    runtimeOnly 'org.postgresql:postgresql'
    compile (group: 'org.springframework.boot', name: 'spring-boot-starter-parent', version: '1.2.1.RELEASE')
    compile "com.google.guava:guava:16+"
    compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25'
    compile group: 'mysql', name: 'mysql-connector-java', version: '8.0.19'
    compile group: 'joda-time', name: 'joda-time', version: '2.3'
    testCompile 'org.evosuite:evosuite-standalone-runtime:1.0.6'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    compile 'org.springframework.boot:spring-boot-starter-tomcat'
    compile("javax.servlet:jstl")
    compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.0'
    compile group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'
    compile("org.apache.tomcat.embed:tomcat-embed-jasper")
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-mail', version: '2.2.5.RELEASE'
    testCompile('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.mockito'
    }
    compile group: 'joda-time', name: 'joda-time', version: '2.3'
    testCompile group: 'org.mockito', name: 'mockito-core', version: '2.23.0'
    compileOnly('org.projectlombok:lombok')

    testCompile 'org.junit.jupiter:junit-jupiter-engine:5.2.0'
    testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc'
    //testImplementation 'org.springframework.security:spring-security-test'
}

test {
    outputs.dir snippetsDir
    useJUnitPlatform()
}

asciidoctor {
    inputs.dir snippetsDir
    dependsOn test
}

anyone knows how to figure it out? Thank you!

like image 923
ziang qiu Avatar asked Mar 23 '20 12:03

ziang qiu


2 Answers

Could you try it with an even newer Mockito version please (2.28.2 or even 3.3.3) - and make sure that no other library pulls in an older version, i.e. look at the dependency tree.

testCompile('org.springframework.boot:spring-boot-starter-test') {
    exclude group: "org.mockito", module: "mockito-core"
}
testCompile("org.mockito:mockito-core:2.28.2")
like image 182
Marco Behler Avatar answered Oct 25 '22 07:10

Marco Behler


You are mocking the Date class in an unusual manner. I'm not sure why you are trying to load through reflection and a specific classloader. Your code doesn't even compile for me.

The normal way to mock a class is just to add .class to the class name. I can mock the Date class non-static methods like this with mockito because it is public.

   @Test
    public void mockDate() {
       Date date = mock(Date.class);
       when(date.toString()).thenReturn("this date");

       String dateString = date.toString();

       assertEquals("this date", dateString);
    }
like image 31
DCTID Avatar answered Oct 25 '22 09:10

DCTID