Exception caused without changing any of the code [duplicate] - exception

I am totally new in javafx!!
I tried a very very simple code and I got stuck.
when I tried to add a button to the layout It does not work.
I know this question may be too simple but I really do not know how to fix it.
I would appreciated if you could help me.
This is my code:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Test extends Application{
Button button;
public static void main(String[] args){
launch(args);
}
#Override
public void start(Stage stage) throws Exception {
stage.setTitle("Title");
StackPane layout = new StackPane();
button = new Button();
layout.getChildren().add(button);
Scene scene = new Scene(layout);
stage.setScene(scene);
stage.show();
}
}
and I got the error:
Exception in Application start method
java.lang.reflect.InvocationTargetException
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:566)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
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:566)
at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.IllegalAccessError: superclass access check failed: class com.sun.javafx.scene.control.ControlHelper (in unnamed module #0x46b3f4cf) cannot access class com.sun.javafx.scene.layout.RegionHelper (in module javafx.graphics) because module javafx.graphics does not export com.sun.javafx.scene.layout to unnamed module #0x46b3f4cf
at java.base/java.lang.ClassLoader.defineClass1(Native Method)
at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)
at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:174)
at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:802)
at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:700)
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:623)
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
at javafx.scene.control.Control.<clinit>(Control.java:86)
at Test.start(Test.java:21)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
... 1 more
Exception running application Test

From the error I'm assuming you're using JavaFX 11 (or at least JavaFX 9+). Note that the ultimate problem is not the InvocationTargetException but the IllegalAccessError:
Caused by: java.lang.IllegalAccessError: superclass access check failed: class com.sun.javafx.scene.control.ControlHelper (in unnamed module #0x46b3f4cf) cannot access class com.sun.javafx.scene.layout.RegionHelper (in module javafx.graphics) because module javafx.graphics does not export com.sun.javafx.scene.layout to unnamed module #0x46b3f4cf
This is telling you code in the "unnamed module" is trying to access internals of the javafx.graphics module. As this is not allowed the error is thrown. But the real problem here is that ControlHelper is in the unnamed module but it's supposed to be in the javafx.controls module, if the package name is anything to go by. This problem is caused by having javafx.graphics on the modulepath but javafx.controls on the classpath.
Make sure you have both modules (and javafx.base) on the --module-path. As your code is not modular (no module-info file) you will also have to tell the module system to resolve it by using:
--add-modules javafx.controls
You don't have to include javafx.graphics in the --add-modules command because javafx.controls requires javafx.graphics (and javafx.graphics requires javafx.base). As all modules are on the modulepath they will be resolved.
How you set these commands is dependent on how you launch your application (e.g. command-line, IDE, Maven, Gradle, etc...).
If you ever make your code modular you won't need to use the --add-modules command, just put the appropriate requires directives in your module-info file. For example:
module app {
requires javafx.controls;
}

Related

How to set maxFileSize for FileUploadFactory when using Joy?

Can someone please let me know how to configure the maxFileSize for fileUploads in Jodd, when using Joy?
I've tried in joy.props, even under [joy.madvoc] section with the earlier working:
madvocConfig.fileUploadFactory.maxFileSize=-1
But have no luck :(
Another question is how to force it, to report error, as without it, got:
java.lang.NullPointerException
com.mycircle.action.CircleAction.add(CircleAction.java:78)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
jodd.madvoc.ActionRequest.invokeActionMethod(ActionRequest.java:256)
jodd.madvoc.ActionRequest.lambda$createExecutionArray$1(ActionRequest.java:226)
jodd.madvoc.ActionRequest.invoke(ActionRequest.java:240)
jodd.madvoc.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:79)
jodd.madvoc.interceptor.ActionInterceptor.apply(ActionInterceptor.java:38)
jodd.madvoc.ActionRequest.invoke(ActionRequest.java:240)
jodd.joy.i18n.I18nInterceptor.intercept(I18nInterceptor.java:46)
jodd.madvoc.interceptor.ActionInterceptor.apply(ActionInterceptor.java:38)
jodd.madvoc.ActionRequest.invoke(ActionRequest.java:240)
jodd.madvoc.ActionRequest.lambda$createExecutionArray$0(ActionRequest.java:209)
jodd.madvoc.ActionRequest.invoke(ActionRequest.java:240)
jodd.madvoc.component.MadvocController.invoke(MadvocController.java:163)
jodd.madvoc.MadvocServletFilter.doFilter(MadvocServletFilter.java:109)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
jodd.decora.DecoraServletFilter.doFilter(DecoraServletFilter.java:144)
After debugging, I figured out that is due to file size limitation 100240 bytes defined in FileUploadFactory and AdaptiveFileUploadFactory as well.
I have a #In FileUpload image; in CircleAction and it become null due to this.
Here is how to do so:
from Joy get to the Madvoc
in Madvoc get the FileUploader component - it's a new one that simply holds a FileUploadFactory instance.
Use it:)
Something like this:
public class MyWebApplication extends JoyContextListener {
#Override
protected JoddJoy createJoy() {
final JoddJoy joy = super.createJoy();
joy.withWebApp(webApp -> {
webApp.withRegisteredComponent(FileUploader.class, fileUploader -> {
AdaptiveFileUploadFactory adaptiveFileUploadFactory =
(AdaptiveFileUploadFactory) fileUploader.get();
adaptiveFileUploadFactory.setMaxFileSize(10000000);
});
});
return joy;
}
}
The seccond way is to use registerComponent and simply pass your implementation of FileUploader.
Atm, it is not possible to set this value from the madvoc config, but I will fix that soon. There is no more madvocConfig - instead you can set each component. So you will be able to do so like this: fileUploader.maxFileSize (after the fix:).

Mockito cannot mock JdbcTemplate

I'm currently working on setting up JUnit tests using Mockito. As of right now, I'm unable to get a very basic test to run:
#ExtendWith(MockitoExtension.class)
public class TestDAO {
private final Logger logger = LoggerFactory.getLogger(TestDAO.class.getName());
#Mock
public JdbcTemplate jdbcTemplate = new JdbcTemplate();
#InjectMocks
private TestDAOImpl dao;
#Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
#BeforeEach
public void init() {
System.out.println("Hello init");
}
#Test
public void getAllEntries() {
System.out.println("hello world");
}
}
For the moment, all I want is to see if it can print out hello world. Every time I run the test, though, I receive an error that:
Underlying exception : java.lang.IllegalArgumentException: object is not an instance of declaring class
Which seems to point to the JdbcTemplate as the culprit. I'm trying to mock that database connection so I can mock CRUD operations later.
This is my first time using Mockito, so any help would be appreciated. The full stack trace is below:
org.mockito.exceptions.base.MockitoException:
Mockito cannot mock this class: class org.springframework.jdbc.core.JdbcTemplate.
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 : 1.8
JVM vendor name : Oracle Corporation
JVM vendor version : 25.5-b02
JVM name : Java HotSpot(TM) Client VM
JVM version : 1.8.0_05-b13
JVM info : mixed mode
OS name : Windows 7
OS version : 6.1
Underlying exception : java.lang.IllegalArgumentException: object is not an instance of declaring class
at org.mockito.junit.jupiter.MockitoExtension.beforeEach(MockitoExtension.java:165)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeBeforeEachCallbacks$0(TestMethodTestDescriptor.java:129)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor$$Lambda$192/20816428.execute(Unknown Source)
at org.junit.jupiter.engine.execution.ThrowableCollector.execute(ThrowableCollector.java:40)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeBeforeMethodsOrCallbacksUntilExceptionOccurs(TestMethodTestDescriptor.java:155)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeBeforeEachCallbacks(TestMethodTestDescriptor.java:128)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:107)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:58)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:113)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor$$Lambda$142/16902902.execute(Unknown Source)
at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:121)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor$$Lambda$145/18524506.accept(Unknown Source)
at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
at java.util.Iterator.forEachRemaining(Iterator.java:116)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:512)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:502)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:121)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor$$Lambda$142/16902902.execute(Unknown Source)
at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:121)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor$$Lambda$145/18524506.accept(Unknown Source)
at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
at java.util.Iterator.forEachRemaining(Iterator.java:116)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:512)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:502)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:121)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor$$Lambda$142/16902902.execute(Unknown Source)
at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:55)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:43)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:170)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:154)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:90)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:74)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Suppressed: java.lang.NullPointerException
at org.mockito.junit.jupiter.MockitoExtension.afterEach(MockitoExtension.java:211)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeAfterEachCallbacks$11(TestMethodTestDescriptor.java:217)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor$$Lambda$196/31005110.execute(Unknown Source)
at org.junit.jupiter.engine.execution.ThrowableCollector.execute(ThrowableCollector.java:40)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeAllAfterMethodsOrCallbacks$13(TestMethodTestDescriptor.java:229)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor$$Lambda$195/6646756.accept(Unknown Source)
at java.util.ArrayList.forEach(ArrayList.java:1234)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeAllAfterMethodsOrCallbacks(TestMethodTestDescriptor.java:227)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeAfterEachCallbacks(TestMethodTestDescriptor.java:216)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:119)
... 49 more
Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$ForTypeArgument.resolve(TypeDescription.java:3083)
at net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$Delegator$Chained.resolve(TypeDescription.java:2868)
at net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$ForTypeArgument.resolve(TypeDescription.java:3056)
at net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$Delegator.asList(TypeDescription.java:2822)
at net.bytebuddy.description.type.TypeDescription$Generic$OfTypeVariable$ForLoadedType.getDeclaredAnnotations(TypeDescription.java:5130)
at net.bytebuddy.description.type.TypeDescription$Generic$OfTypeVariable$Symbolic.getDeclaredAnnotations(TypeDescription.java:4941)
at net.bytebuddy.description.type.TypeDescription$Generic$OfTypeVariable$WithAnnotationOverlay.getDeclaredAnnotations(TypeDescription.java:5204)
at net.bytebuddy.implementation.attribute.AnnotationAppender$ForTypeAnnotations.apply(AnnotationAppender.java:639)
at net.bytebuddy.implementation.attribute.AnnotationAppender$ForTypeAnnotations.onTypeVariable(AnnotationAppender.java:611)
at net.bytebuddy.implementation.attribute.AnnotationAppender$ForTypeAnnotations.onTypeVariable(AnnotationAppender.java:333)
at net.bytebuddy.description.type.TypeDescription$Generic$OfTypeVariable.accept(TypeDescription.java:4852)
at net.bytebuddy.implementation.attribute.AnnotationAppender$ForTypeAnnotations.onParameterizedType(AnnotationAppender.java:601)
at net.bytebuddy.implementation.attribute.AnnotationAppender$ForTypeAnnotations.onParameterizedType(AnnotationAppender.java:333)
at net.bytebuddy.description.type.TypeDescription$Generic$OfParameterizedType.accept(TypeDescription.java:4372)
at net.bytebuddy.implementation.attribute.MethodAttributeAppender$ForInstrumentedMethod.apply(MethodAttributeAppender.java:183)
at net.bytebuddy.implementation.attribute.MethodAttributeAppender$Compound.apply(MethodAttributeAppender.java:425)
at net.bytebuddy.dynamic.scaffold.TypeWriter$MethodPool$Record$ForDefinedMethod$WithBody.applyAttributes(TypeWriter.java:617)
at net.bytebuddy.dynamic.scaffold.TypeWriter$MethodPool$Record$ForDefinedMethod$WithBody.applyBody(TypeWriter.java:609)
at net.bytebuddy.dynamic.scaffold.TypeWriter$MethodPool$Record$ForDefinedMethod.apply(TypeWriter.java:528)
at net.bytebuddy.dynamic.scaffold.TypeWriter$Default$ForCreation.create(TypeWriter.java:4167)
at net.bytebuddy.dynamic.scaffold.TypeWriter$Default.make(TypeWriter.java:1653)
at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:183)
at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:163)
at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase.make(DynamicType.java:2669)
at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase$Delegator.make(DynamicType.java:2771)
at org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:128)
at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)
at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)
at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:137)
at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:344)
at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:159)
at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:353)
at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)
at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:71)
at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:42)
at org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.createMock(ByteBuddyMockMaker.java:25)
at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)
at org.mockito.internal.MockitoCore.mock(MockitoCore.java:69)
at org.mockito.Mockito.mock(Mockito.java:1895)
at org.mockito.internal.configuration.MockAnnotationProcessor.processAnnotationForMock(MockAnnotationProcessor.java:41)
at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:19)
at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:16)
at org.mockito.internal.configuration.IndependentAnnotationEngine.createMockFor(IndependentAnnotationEngine.java:38)
at org.mockito.internal.configuration.IndependentAnnotationEngine.process(IndependentAnnotationEngine.java:62)
at org.mockito.internal.configuration.InjectingAnnotationEngine.processIndependentAnnotations(InjectingAnnotationEngine.java:57)
at org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:41)
at org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:69)
at org.mockito.internal.framework.DefaultMockitoSession.<init>(DefaultMockitoSession.java:36)
at org.mockito.internal.session.DefaultMockitoSessionBuilder.startMocking(DefaultMockitoSessionBuilder.java:78)
... 56 more
Please recheck your imports and don't mix JUnit 4 and JUnit 5, it may be the source of your problem.
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.jdbc.core.JdbcTemplate;
#ExtendWith ( MockitoExtension.class )
public class SampleTest {
#Mock
private JdbcTemplate jdbcTemplate = new JdbcTemplate();
#InjectMocks
private TestObject testObject;
#BeforeEach
public void init() {
System.out.println( "Hello init" );
}
#Test
public void getAllEntries() {
System.out.println( "hello world" );
}
}
It is working perfectly with my example. Be careful with #Test annotation - it has to be JUnit 5 annotation, moreover #Rule annotation doesn't exist in JUnit 5.
If it won't help, please show us your dependencies with versions.

Powermock - Unable to mock ScheduledExecutorService

I am unable to mock the ScheduledExcecutorService. Unsure where I am making the mistake. One weird part about the exception is "Cannot find method schedule in Object hierarchy", why is it trying to find method in Object class instead of ScheduledExecutorService?
Any help would be appreciated. Thanks in advance.
#RunWith(PowerMockRunner.class)
#PrepareForTest({ ScheduledExecutorService.class, GenericCache.class, ConfigurationDAO.class, ScheduledFuture.class })
#PowerMockIgnore("javax.management.*")
public class CacheManagerTestCase {
// Fields
#Mock
private ScheduledExecutorService mockScheduledExecutorService;
#Mock
private ScheduledFuture scheduledFutureMock;
// Within Test method
when(mockScheduledExecutorService
.schedule(any(Runnable.class), anyLong(), eq(TimeUnit.SECONDS)))
.thenReturn(scheduledFutureMock);
When running the above code, following exception is thrown
org.powermock.reflect.exceptions.MethodNotFoundException: No methods matching the name(s) schedule were found in the class hierarchy of class java.lang.Object.
at org.powermock.reflect.internal.WhiteboxImpl.getMethods(WhiteboxImpl.java:1720)
at org.powermock.reflect.internal.WhiteboxImpl.getMethods(WhiteboxImpl.java:1745)
at org.powermock.reflect.internal.WhiteboxImpl.getBestMethodCandidate(WhiteboxImpl.java:983)
at org.powermock.core.MockGateway$MockInvocation.findMethodToInvoke(MockGateway.java:317)
at org.powermock.core.MockGateway$MockInvocation.init(MockGateway.java:356)
at org.powermock.core.MockGateway$MockInvocation.<init>(MockGateway.java:307)
at org.powermock.core.MockGateway.doMethodCall(MockGateway.java:142)
at org.powermock.core.MockGateway.methodCall(MockGateway.java:125)
at CacheManagerTestCase.testPeriodicRefreshPropertyFalse(CacheManagerTestCase.java:82)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
0 matchers expected, 3 recorded:
-> at CacheManagerTestCase.testPeriodicRefreshPropertyFalse(CacheManagerTestCase.java:82)
-> at CacheManagerTestCase.testPeriodicRefreshPropertyFalse(CacheManagerTestCase.java:82)
-> at CacheManagerTestCase.testPeriodicRefreshPropertyFalse(CacheManagerTestCase.java:82)
This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));

PowerMockito throwing exception when mocking static method of an enum and using that enum object inside a switch statement

I have a enum MyEnum.java which has one static method.
//MyEnum.java
enum MyEnum {
ONE("one"),
TWO("two");
private String value;
MyEnum(String value){
this.value=value;
}
public static MyEnum getMyEnum(String value){
for(MyEnum myEnum : MyEnum.values()){
if(myEnum.value.equalsIgnoreCase(value))
return myEnum;
}
return null;
}
}
I am using PowerMock to mock static methods of this enum. I have included all the necessary conditions like
#Runwith(PowerMockRunner.class)
#PrepareForTest(MyEnum.class)
//Test function
PowerMockito.mockStatic(MyEnum.class);
It all works fine. But if I am using switch method for the object of enum, then it throws the exception.
MyEnum enum = MyEnum.ONE;
switch(enum){
case ONE:
break
}
This code is throwing the following exception.
java.lang.ExceptionInInitializerError
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:191)
at javassist.runtime.Desc.getClassObject(Desc.java:43)
at javassist.runtime.Desc.getClazz(Desc.java:52)
at com.newshunt.shared.presenters.tests.DummyTest.testStaticMethod(DummyTest.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:89)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:97)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:106)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: java.lang.NullPointerException
at com.newshunt.shared.presenters.tests.DummyTest$1.<clinit>(DummyTest.java:26)
... 37 more
Process finished with exit code -1
Even from the logs it is not clear, what is causing this exception to happen? Anybody else encountered similar issues before ?
My recommendation: consider not using PowerMock.
PowerMock looks like the solution to many problems; but rather sooner than later, it can be the cause of much more problems. It breaks coverage, it makes it harder to change the underlying JVM, and so on.
Seriously: if your design can only be tested with PowerMock, this is very often a clear indication that your design is bad. So: focus on reworking your code under test!
In your case: I would start questioning the need of having a static method on an enum. So, in other words: what is the problem you want to address with this code?
But to answer the actual question: you have to understand that enum constants are represented as inner classes themselves. Therefore you have to use the fullyQualifiedName property for #PrepareForTest. See this newer question for an example.

Error loading google maps v3 in gwt

I am searching for a library to visualize data as glyphs over a map. Therefore I thought of using google maps api v3 in gwt and dwar the glyohs as an overlay overlay.
Unfortunately I couldn't find any working sample code to get started.
I followed this tutorial
and while executing the project I got this Error:
Unable to load module entry point
classcom.example.google.gwt.mapstutorial.client.SimpleMaps (see associated exception or
details)
java.lang.RuntimeException: Deferred binding failed for
'com.google.gwt.maps.client.impl.MapOptionsImpl' (did you forget to inherit a required module?)
at com.google.gwt.dev.shell.GWTBridgeImpl.create(GWTBridgeImpl.java:53)
at com.google.gwt.core.client.GWT.create(GWT.java:97)
at com.google.gwt.maps.client.impl.MapOptionsImpl.<clinit>(MapOptionsImpl.java:31)
at com.google.gwt.maps.client.MapOptions.<init>(MapOptions.java:40)
at com.example.google.gwt.mapstutorial.client.SimpleMaps.onModuleLoad(SimpleMaps.java:15)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.gwt.dev.shell.ModuleSpace.onLoad(ModuleSpace.java:396)
at com.google.gwt.dev.shell.OophmSessionHandler.loadModule(OophmSessionHandler.java:200)
at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:525)
at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:363)
at java.lang.Thread.run(Unknown Source)Caused by: java.lang.IncompatibleClassChangeError: Found interface com.google.gwt.core.ext.typeinfo.JClassType, but class was expected
at com.google.gwt.jsio.rebind.JSWrapperGenerator.generate(JSWrapperGenerator.java:276)
at com.google.gwt.core.ext.GeneratorExtWrapper.generate(GeneratorExtWrapper.java:48)
at com.google.gwt.core.ext.GeneratorExtWrapper.generateIncrementally(GeneratorExtWrapper.java:60)
at com.google.gwt.dev.javac.StandardGeneratorContext.runGeneratorIncrementally(StandardGeneratorContext.java:647)
at com.google.gwt.dev.cfg.RuleGenerateWith.realize(RuleGenerateWith.java:41)
at com.google.gwt.dev.shell.StandardRebindOracle$Rebinder.rebind(StandardRebindOracle.java:78)
at com.google.gwt.dev.shell.StandardRebindOracle.rebind(StandardRebindOracle.java:268)
at com.google.gwt.dev.shell.ShellModuleSpaceHost.rebind(ShellModuleSpaceHost.java:141)
at com.google.gwt.dev.shell.ModuleSpace.rebind(ModuleSpace.java:585)
at com.google.gwt.dev.shell.ModuleSpace.rebindAndCreate(ModuleSpace.java:455)
at com.google.gwt.dev.shell.GWTBridgeImpl.create(GWTBridgeImpl.java:49)
at com.google.gwt.core.client.GWT.create(GWT.java:97)
at com.google.gwt.maps.client.impl.MapOptionsImpl.<clinit>(MapOptionsImpl.java:31)
at com.google.gwt.maps.client.MapOptions.<init>(MapOptions.java:40)
at com.example.google.gwt.mapstutorial.client.SimpleMaps.onModuleLoad(SimpleMaps.java:15)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.gwt.dev.shell.ModuleSpace.onLoad(ModuleSpace.java:396)
at com.google.gwt.dev.shell.OophmSessionHandler.loadModule(OophmSessionHandler.java:200)
at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:525)
at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:363)
at java.lang.Thread.run(Unknown Source)
Could anyone help me out here, or does anyone has another suggestion for a library to use in gwt, thanks!
Here is my Code:
package com.example.google.gwt.mapstutorial.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.maps.client.MapOptions;
import com.google.gwt.maps.client.MapTypeId;
import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.base.LatLng;
import com.google.gwt.user.client.ui.RootPanel;
public class SimpleMaps implements EntryPoint {
private MapWidget mapWidget;
// GWT module entry point method.
public void onModuleLoad() {
final MapOptions options = new MapOptions();
// Zoom level. Required
options.setZoom(8);
// Open a map centered on Cawker City, KS USA. Required
options.setCenter(new LatLng(39.509, -98.434));
// Map type. Required.
options.setMapTypeId(new MapTypeId().getRoadmap());
// Enable maps drag feature. Disabled by default.
options.setDraggable(true);
// Enable and add default navigation control. Disabled by default.
options.setNavigationControl(true);
// Enable and add map type control. Disabled by default.
options.setMapTypeControl(true);
mapWidget = new MapWidget(options);
mapWidget.setSize("800px", "600px");
// Add the map to the HTML host page
RootPanel.get("mapsTutorial").add(mapWidget);
}
}