I have some trouble with launching a javafx application. To explain, I wrote a code that worked but I was on Ubuntu 19.04 and I decided to reinstall my Linux version (20.04). I copied my code and reinstalled e(fx)clipse, scenebuilder, openjfx, and imported the same jfxrt.jar but nothing worked. I can't manage to launch javafx application, even if the code is empty (ig code). Oh and I have to use java 8 for this homework.
Can you help me please?
Here is my code
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
public class LaunchApplication extends Application {
public static void main(String[] args) {
launch(args);
}
//Empty but still error
#Override
public void start(Stage arg0) throws Exception {
}
//Old code, doesnt work anymore
// #Override
// public void start(Stage primaryStage) throws Exception {
// try {
//
// FXMLLoader loader = new FXMLLoader();
// loader.setLocation(getClass().getResource("view/Login.fxml"));
// Parent root = loader.load();
//
// Scene scene = new Scene(root);
// primaryStage.setScene(scene);
// primaryStage.setResizable(true);
// primaryStage.show();
//
// } catch (Exception e) {
// System.out.println(e);
// }
//
// }
}
And there my error when running it
Exception in thread "main" java.lang.reflect.InvocationTargetException
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:498)
at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: java.lang.NoSuchMethodError: <init>
at com.sun.javafx.tk.quantum.QuantumToolkit.startup(QuantumToolkit.java:288)
at com.sun.javafx.application.PlatformImpl.startup(PlatformImpl.java:211)
at com.sun.javafx.application.LauncherImpl.startToolkit(LauncherImpl.java:675)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:337)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
... 5 more
Caused by: java.lang.NoSuchMethodError: <init>
at java.lang.ClassLoader$NativeLibrary.load(Native Method)
at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1934)
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1817)
at java.lang.Runtime.load0(Runtime.java:810)
at java.lang.System.load(System.java:1088)
at com.sun.glass.utils.NativeLibLoader.loadLibraryInternal(NativeLibLoader.java:107)
at com.sun.glass.utils.NativeLibLoader.loadLibrary(NativeLibLoader.java:39)
at com.sun.glass.ui.gtk.GtkApplication.lambda$new$5(GtkApplication.java:156)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.glass.ui.gtk.GtkApplication.<init>(GtkApplication.java:140)
at com.sun.glass.ui.gtk.GtkPlatformFactory.createApplication(GtkPlatformFactory.java:41)
at com.sun.glass.ui.Application.run(Application.java:146)
at com.sun.javafx.tk.quantum.QuantumToolkit.startup(QuantumToolkit.java:278)
... 9 more
```
Related
I recently started learning JavaFX and my class was given the following assignment:
Write a program that displays four images in a grid pane.
Here is my code:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
public class Ch_14_Ex_1 extends Application {
#Override //Override the start method in the Application class
public void start(Stage primaryStage) {
//Create a pane to hold the image views
GridPane pane = new GridPane();
//Place nodes in the pane
pane.add(new ImageView(new Image("image/ukFlag1.gif")), 0, 0);
pane.add(new ImageView(new Image("image/canadaFlag1.gif")), 1, 0);
pane.add(new ImageView(new Image("image/chineseFlag1.gif")), 0, 1);
pane.add(new ImageView(new Image("image/usaFlag1.gif")), 1, 1);
//Create a scene and place it in the stage
Scene scene = new Scene(pane);
primaryStage.setTitle("Ch_14_Ex_1"); //Set the stage title
primaryStage.setScene(scene); //Place the scene in the stage
primaryStage.show(); //Display the stage
}
}
The program compiles fine but whenever I try to run the program I get the following error and i'm not sure how to fix it.
Exception in Application start method
Exception in thread "JavaFX BlueJ Helper" java.lang.RuntimeException:
Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalArgumentException: Invalid URL: Invalid URL or resource not found
at javafx.scene.image.Image.validateUrl(Image.java:1118)
at javafx.scene.image.Image.<init>(Image.java:620)
at Ch_14_Ex_1.start(Ch_14_Ex_1.java:16)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
... 1 more
Caused by: java.lang.IllegalArgumentException: Invalid URL or resource not found
at javafx.scene.image.Image.validateUrl(Image.java:1110)
... 11 more
You can set the resources folder in your project in case you wanna wrap it in your jar file and load them like so
new Image(getClass.getResourceAsStream("image/yourImage.gif"))
OR
If those images are not in your resources you can load them like so
new Image("file:image/yourimage.gif")
I have also run into some problems trying to get my JavaFX program to run. Like some of the others, I keep getting an error of java.lang.NullPointerException: Location is required. The fxml file is in the Application package. I've tried all the remedies I've found in here, but maybe I'm missing something? Here is my code
package application;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
Parent root = FXMLLoader.load(getClass().getResource("application/Main.fxml"));
Scene scene = new Scene(root, 400, 400);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
And here is the Error
java.lang.NullPointerException: Location is required.
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3207)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
at application.Main.start(Main.java:18)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
Any help would be much appreciated. Thanks in advance
I lost an entire day battling with this issue in Netbeans. This is how I solved it : Firstly, I put the fxml file in the same package with main (though it can work even in separate packages). Secondly, I used getClassLoader() specifying the path of the file. Here's the code :`
public class Main {
public static void main(String[] args) {
System.out.println("Test = "+Main.class.getClassLoader().getResource("FXMLDocument.fxml"));`
After Running the project, here's the output : ....NetBeansProjects/JavaFXApplicationTest/dist/JavaFXApplicationTest.jar!/FXMLDocument.fxml
Note that Running the file alone was generating an error before.
this will work:
"/application/Main.fxml"
you just need to add a /
Solved the problem by dragging and dropping Main.fxml in src folder.
Help! I'm stuck.. I try to run my main javafx app
Here is my codes;
#Override
public void start(Stage primaryStage) throws Exception {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/com/utmkl/fxml/SimulatorDisplay.fxml"));
Parent content = (Parent)loader.load();
primaryStage.setResizable(false);
primaryStage.initStyle(StageStyle.UTILITY);
primaryStage.setScene(new Scene(content));
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
Below is my folder structure:
picture Folder structure
Below is the error
java.lang.IllegalStateException: Location is not set.
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2434)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409)
at com.utmkl.VMCSManager.start(VMCSManager.java:43)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:745)
I've found the answer..
the resource need to be in the same folder structure as main class
Here is my Maven-JavaFX Folder structure
VMCS
- src/main/java
- com.utmkl
VMCSManager.java
- src/main/resources
- com.utmkl.fxml
SimulatorDisplay.fxml
So, the correct code (which success to run)
VMCSManager.java
#Override
public void start(Stage primaryStage) throws Exception {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("fxml/SimulatorDisplay.fxml"));
Parent content = loader.load();
Scene scene = new Scene(content);
primaryStage.setResizable(false);
primaryStage.initStyle(StageStyle.UTILITY);
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
Even though you do set a location with loader.setLocation(getClass().getResource("/com/utmkl/fxml/ControllerDisplay.fxml")); it is likely that the resource URL doesn't actually refer to an existing resource on the classpath.
If you add System.out.println(getClass().getResource("/com/utmkl/fxml/ControllerDisplay.fxml")); to your code I think it will print null as a result.
I'm developing an OSGI (Equinox) Based-System and i came across JavaFX, i was trying the e(fx)clipse {OSGI bundle project} and i wrote a simple test project, but it is giving me some compilation errors.
i have a main class :
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class main extends Application {
private static main _main ;
public main () {
_main = this;
}
public static main Get_Main(){
return _main;
}
#Override
public void start(Stage primaryStage)
{
try
{
FXMLLoader loader = new FXMLLoader();
loader.setLocation(main.class.getResource("fxml.fxml"));
primaryStage.setScene(new Scene(loader.load()));
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and i have a controller for the FXML
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
public class controller {
#FXML
private AnchorPane _AnchorPane;
#FXML
private Button _Btn;
#FXML
private void initialize() {
_AnchorPane.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
_AnchorPane.setStyle("-fx-background-color:red");
}
});
}
#FXML
private void _BtnClick() {
_AnchorPane.setStyle("-fx-background-color:blue");
}
}
and an Activator for the bundle
import javafx.stage.Stage;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class aCTIVATOR implements BundleActivator {
private Stage _stage = new Stage();
private main _main;
#Override
public void start(BundleContext context) throws Exception {
_main = main.Get_Main();
_main.start(_stage);
}
#Override
public void stop(BundleContext context) throws Exception {
_stage.close();
}
}
and this is my manifest file :
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name:
Bundle-SymbolicName: root
Bundle-Version: 1.0.0.qualifier
Bundle-RequiredExecutionEnvironment: JavaSE-1.8
Import-Package: javafx.animation;version="2.0.0",
javafx.application;version="2.0.0",
javafx.beans;version="2.0.0",
javafx.beans.binding;version="2.0.0",
javafx.beans.property;version="2.0.0",
javafx.beans.value;version="2.0.0",
javafx.collections;version="2.0.0",
javafx.concurrent;version="2.0.0",
javafx.event;version="2.0.0",
javafx.fxml;version="2.0.0",
javafx.geometry;version="2.0.0",
javafx.scene;version="2.0.0",
javafx.scene.chart;version="2.0.0",
javafx.scene.control;version="2.0.0",
javafx.scene.control.cell;version="2.0.0",
javafx.scene.effect;version="2.0.0",
javafx.scene.image;version="2.0.0",
javafx.scene.input;version="2.0.0",
javafx.scene.layout;version="2.0.0",
javafx.scene.media;version="2.0.0",
javafx.scene.paint;version="2.0.0",
javafx.scene.shape;version="2.0.0",
javafx.scene.text;version="2.0.0",
javafx.scene.transform;version="2.0.0",
javafx.scene.web;version="2.0.0",
javafx.stage;version="2.0.0",
javafx.util;version="2.0.0"
Bundle-Activator: aCTIVATOR
Require-Bundle: org.eclipse.osgi;bundle-version="3.10.0"
so when i go to the Run-Configuration, i choose OSGI-FrameWork and select the
project
org.eclipse.osgi
org.eclipse.fx.javafx
org.eclipse.fx.osgi
and finally it si giving my this compilation error:
!SESSION 2014-10-21 13:32:14.128 -----------------------------------------------
eclipse.buildId=unknown
java.version=1.8.0_20
java.vendor=Oracle Corporation
BootLoader constants: OS=linux, ARCH=x86_64, WS=gtk, NL=en_US
Command-line arguments: -dev file:/home/hany/workspace/JavaFX/.metadata/.plugins/org.eclipse.pde.core/New_configuration/dev.properties -os linux -ws gtk -arch x86_64 -consoleLog -console
!ENTRY root 4 0 2014-10-21 13:32:14.618
!MESSAGE FrameworkEvent ERROR
!STACK 0
org.osgi.framework.BundleException: Error starting module.
at org.eclipse.osgi.container.Module.doStart(Module.java:567)
at org.eclipse.osgi.container.Module.start(Module.java:429)
at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1551)
at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1531)
at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.doContainerStartLevel(ModuleContainer.java:1502)
at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1445)
at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1)
at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:340)
Caused by: java.lang.NoClassDefFoundError: javafx/stage/Stage
at aCTIVATOR.<init>(aCTIVATOR.java:8)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at java.lang.Class.newInstance(Class.java:433)
at org.eclipse.osgi.internal.framework.BundleContextImpl.loadBundleActivator(BundleContextImpl.java:755)
at org.eclipse.osgi.internal.framework.BundleContextImpl.start(BundleContextImpl.java:706)
at org.eclipse.osgi.internal.framework.EquinoxBundle.startWorker0(EquinoxBundle.java:928)
at org.eclipse.osgi.internal.framework.EquinoxBundle$EquinoxModule.startWorker(EquinoxBundle.java:317)
at org.eclipse.osgi.container.Module.doStart(Module.java:558)
... 8 more
Caused by: java.lang.ClassNotFoundException: javafx.stage.Stage cannot be found by osgi.identity; osgi.identity="root"; type="osgi.bundle"; version:Version="1.0.0.qualifier"
at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:365)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:331)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:323)
at org.eclipse.osgi.internal.loader.ModuleClassLoader.loadClass(ModuleClassLoader.java:160)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 19 more
Root exception:
java.lang.NoClassDefFoundError: javafx/stage/Stage
at aCTIVATOR.<init>(aCTIVATOR.java:8)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at java.lang.Class.newInstance(Class.java:433)
at org.eclipse.osgi.internal.framework.BundleContextImpl.loadBundleActivator(BundleContextImpl.java:755)
at org.eclipse.osgi.internal.framework.BundleContextImpl.start(BundleContextImpl.java:706)
at org.eclipse.osgi.internal.framework.EquinoxBundle.startWorker0(EquinoxBundle.java:928)
at org.eclipse.osgi.internal.framework.EquinoxBundle$EquinoxModule.startWorker(EquinoxBundle.java:317)
at org.eclipse.osgi.container.Module.doStart(Module.java:558)
at org.eclipse.osgi.container.Module.start(Module.java:429)
at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1551)
at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1531)
at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.doContainerStartLevel(ModuleContainer.java:1502)
at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1445)
at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1)
at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:340)
Caused by: java.lang.ClassNotFoundException: javafx.stage.Stage cannot be found by osgi.identity; osgi.identity="root"; type="osgi.bundle"; version:Version="1.0.0.qualifier"
at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:365)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:331)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:323)
at org.eclipse.osgi.internal.loader.ModuleClassLoader.loadClass(ModuleClassLoader.java:160)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 19 more
!ENTRY org.eclipse.osgi 4 0 2014-10-21 13:32:14.621
!MESSAGE Bundle root_1.0.0.qualifier [4] is not active.
!ENTRY org.eclipse.osgi 4 0 2014-10-21 13:32:14.622
!MESSAGE Could not find bundle: org.eclipse.equinox.console
!STACK 0
org.osgi.framework.BundleException: Could not find bundle: org.eclipse.equinox.console
at org.eclipse.core.runtime.internal.adaptor.ConsoleManager.checkForConsoleBundle(ConsoleManager.java:58)
at org.eclipse.core.runtime.adaptor.EclipseStarter.startup(EclipseStarter.java:323)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:222)
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 org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:636)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:591)
at org.eclipse.equinox.launcher.Main.run(Main.java:1450)
at org.eclipse.equinox.launcher.Main.main(Main.java:1426)
!!!!!!!(this was a long one)
So any idea or help about this?
The reason you see the "java.lang.NoClassDefFoundError" is that Equinox does not consult the Ext-classpath and most likely you don't tell Equinox to use our adaptor hooks who make equinox consult that path.
What you need to do is to:
Ensure that you have org.eclipse.fx.osgi fragment in your launch
Make sure you pass -Dosgi.framework.extensions=org.eclipse.fx.osgi as VM arguments in your launch config
(Update) Preferred option launch with -Dorg.osgi.framework.bundle.parent=ext
Now that I've answered your real question. I can not end with a final note on your style of asking and replying to people. This is not good and I've thought multiple times about whether I should answer. Stop putting exclamation marks in your questions and reply and before putting someone down think twice if this the correct way to talk to someone who tried to help you!
I had been using jmock with seam all these days, but its not sufficient to mock final/static/enums. So I tried working with JMockit. However everytime I run, I get NPE. Can't even debug, below is sample code
public class TestJmockit extends SeamTest {
#Mocked Dependency dependencyInCodeToTest;
CodeToTest bean = new CodeToTest();
#Test
public void testSaveSectionChangesJMockit() throws Exception {
new AbstractSeamTest.ComponentTest() {
#Override
protected void testComponents() throws Exception {
new NonStrictExpectations()
{
{
dependencyInCodeToTest.getLabel(); result = "Normal";
}
};
bean.execute();
}
}.run();
}
}
Actual Code..
package com.abc.action.account.information;
import com.abc.vo.account.ExternalAccountStatus;
import com.abc.vo.account.information.ExternalAccountStatusClosedInfo;
import com.abc.vo.account.information.ExternalAccountStatusInfo;
import mockit.Mocked;
import mockit.NonStrictExpectations;
import org.jboss.seam.mock.AbstractSeamTest;
import org.jboss.seam.mock.SeamTest;
import org.junit.Test;
public class ConsumerAccountInformationActionTestJmockit extends SeamTest {
#Mocked ExternalAccountStatus mockExternalAccountStatus;
#Mocked ExternalAccountStatusInfo mockExternalAccountStatusInfo;
// ConsumerAccountInformationAction bean = new ConsumerAccountInformationAction();
#Test
public void testSaveSectionChangesJMockit() throws Exception {
new AbstractSeamTest.ComponentTest() {
#Override
protected void testComponents() throws Exception {
new NonStrictExpectations()
{
{
mockExternalAccountStatus.getLabel(); result = "Normal";
mockExternalAccountStatusInfo.getClosedInfo(); result = new ExternalAccountStatusClosedInfo();
}
};
// bean.saveSectionChanges();
}
}.run();
}
}
If I put a breakpoint at class declaratiom (Public Class Consumer..), stepping over to next line causes NPE. If I take out the commented lines in the code, it fails at the first uncommented line.
I am using Java 1.6 and IntelliJ IDE. Wonder if it has to do with IDE configuration.
With TestNG I dont even get the stack trace, with JUnit I see the below..
java.lang.NullPointerException
at org.jboss.seam.servlet.ServletApplicationMap.get(ServletApplicationMap.java:54)
at org.jboss.seam.contexts.BasicContext.get(BasicContext.java:49)
at org.jboss.seam.contexts.BasicContext.get(BasicContext.java:44)
at org.jboss.seam.core.Init.instance(Init.java:117)
at org.jboss.seam.contexts.BusinessProcessContext.<init>(BusinessProcessContext.java:47)
at org.jboss.seam.contexts.TestLifecycle.beginTest(TestLifecycle.java:35)
at org.jboss.seam.mock.AbstractSeamTest$ComponentTest.run(AbstractSeamTest.java:159)
at com.billmelater.csa.action.account.information.ConsumerAccountInformationActionTestJmockit.testSaveSectionChangesJMockit(ConsumerAccountInformationActionTestJmockit.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:73)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:46)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:180)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:41)
at org.junit.runners.ParentRunner$1.evaluate(ParentRunner.java:173)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.ParentRunner.run(ParentRunner.java:220)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:71)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:199)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:62)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Process finished with exit code 255
General Objection: mocking is there to isolate you from external code,
especially from those coming from your server wendor ( like AbstractSeamtest ) - so
you do not have to initialize them or have server runing or whatever.
Treat mocked test as saved debug session. In your case you like to assure (I'm guessing), that method
bean.saveSectionChanges();
interacts correctly with seam infrastructure, or other collaborators. This is easily achieved by something like:
public static testProperInteraction(#Mocked final Collaborator collaborator) {
new Expectations() {
{
collaborator.doThis(with some parameters);
returns(something you like);
}
};
Bean bean = new Bean(collaborator);
assertSomething(bean.saveSessionChanges());
// nothing else shall be called
new FullVerifications() {
{
}
};
}