Im in IntellijIdea, trying to extract some logic from my tests to be reused in others. The problem is everytime I create another class (in the same test package); the test runs fine, but then stops finding the other file, throwing a 'java: cannot find symbol' error. It seems to happen whenever I make changes to the orginal file. It's the same for any new class I try to create, not just the abstract parent class in this example.
I've searched similar questions here, and because the test works at first this seemed promising IntelliJ can't find classes in same package when compiling. But, there were no scripts excepted when I checked.
Currently I'm running my unit tests by just right clicking my tests folder and selecting 'Run all tests', or just running the individual test the same way.
I would be very grateful for any insights.
EDIT: Thanks for fixing the image formatting issue for me.
I also added the source code for the two classes as requested. I still feel like leaving the images is a good idea though, as I mainly meant to communicate the project structure and errors. Also, I want to stress that the problem is code independend I would say, since it persists with any two files.
Note that nonsensical line 51 of the InfoTest ("line = line;") was added to replicate the error. Any change to the original class causes any other class in the package to not be found. You can even see it's not present in the image showing the test running fine.
Extracted class:
package CommandProcessing;
import GameLogic.Game;
import org.junit.jupiter.api.BeforeEach;
import java.lang.reflect.Field;
import static org.junit.jupiter.api.Assertions.fail;
public abstract class InputSimulator {
protected Game game;
protected CommandParser commandParser;
#BeforeEach
void setUp() {
game = new Game();
try {
Class<?> gameClass = game.getClass();
Field cmdField = gameClass.getDeclaredField("commandParser");
cmdField.setAccessible(true);
commandParser = (CommandParser)cmdField.get(game);
} catch (Exception e){
fail(e);
}
}
protected void simulateInput(String input){
commandParser.handleInput(input);
}
class InputTestCase {
private String input;
private String expected;
public InputTestCase(String input, String expected){
this.input = input;
this.expected = expected;
}
public String getInput() { return input; }
public String getExpected() { return expected; }
}
}
Original class:
package CommandProcessing;
import Database.*;
import GameLogic.Game;
import Ship.*;
import IOHandler.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Field;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.*;
class InfoTest extends InputSimulator {
private final InputTestCase[] testCases =
{
new InputTestCase("info cpit", "Cockpit - health: 100.0, shields: 100.0"),
new InputTestCase("info engi", "Engine - health: 100.0, shields: 100.0"),
new InputTestCase("info shld", "Shields - health: 100.0, shields: 100.0"),
new InputTestCase("info weap", "Weapons - health: 100.0, shields: 100.0"),
new InputTestCase("info tank", "FuelTank - health: 100.0, shields: 100.0"),
new InputTestCase("info carg", "CargoBay - health: 100.0, shields: 100.0")
};
#Test
void printPartsOnInfo() {
simulateInput("info");
ArrayList<String> expected = new ArrayList<String>();
expected.add(game.dbAccess().getMessage(Message.Info));
for(PartType part : PartType.values()){
String partString = part.toString();
expected.add(partString);
}
ArchiveAccess archiveAccess = game.getArchiveAccess();
ArrayList<String> lines = archiveAccess.getOutput();
assertEquals(expected, lines);
}
#Test
void printPartDetails() {
for (InputTestCase testCase : testCases) {
simulateInput(testCase.getInput());
ArchiveAccess archiveAccess = game.getArchiveAccess();
String line = archiveAccess.lastOutput();
line = line;
assertEquals(testCase.getExpected(), line);
}
}
}
All errors:
Test running fine the first time:
No Excludes:
So, the problem was that the test root folder was in my source folder!
I actually had the right answer at one time, but read it badly:
How to create a test directory in Intellij 13?.
The test root folder should be next to a main folder which should be the one marked as the source root, not their parent 'src' folder. I had marked this parent directory as the source root - that is to say, the default source root was already called 'src' and I managed to put my test root folder in it, a project structure suspiciously hard to replicate as it would turn out. I got confused because of the naming.
It's a mystery to me how I got it to work in the first place, because when I tried to reproduce the problem it required some detours to get my test root inside my source root. And even then the tests couldn't even find the JUnit package at runtime (they did compile fine though).
Related
I am trying to call the webservice for my application. If I call it in a sample project it is working perfectly fine. But when I merge it with My Java FX it is giving me so many errors. Web Service Client is auto generated using the Eclipse. I am trying to call the Methods only. Can Anyone help me?
Error: **Correction** I have edited it and I am using now JAVASE-15 and JVAFX-SDK 11.0.2
The package javax.xml.namespace is accessible from more than one module: java.xml, jaxrpc
Correction Update 2: I have removed Java.xml dependencies and module-info file as well.
but the new error is this
**Error: Could not find or load main class gload.Main
Caused by: java.lang.NoClassDefFoundError: javafx/application/Application**
and IF I keep the module info file it shows:
**Error occurred during initialization of boot layer
java.lang.module.FindException: Module javafx.graphics not found, required by gload**
Model:
package gload.model;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.swing.JOptionPane;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.datacontract.schemas._2004._07.PE_PPER_MyPdmWebServiceClient_Data.CustomerItem;
import org.datacontract.schemas._2004._07.PE_PPER_MyPdmWebServiceClient_Data.Result;
import org.tempuri.IService;
import org.tempuri.ServiceLocator;
public class PdmData
{
public String scode;
public boolean state = false;
public static String CdfFile;
public static String pdflocation;
public static String Custom_Ci;
public static String Generic_Ci;
public static String Mp_ref;
public static String Interface;
public static String Comments;
public static String PersoAppli;
public static String Code;
public static String Revision;
public static String Customer_Name;
public static String Customer_reference;
public static String getCode() {
return Code;
}
public static void setCode(String code) {
Code = code;
}
public static String getRevision() {
return Revision;
}
public static void setRevision(String revision) {
Revision = revision;
}
public static String getCustomer_Name() {
return Customer_Name;
}
public static void setCustomer_Name(String customer_Name) {
Customer_Name = customer_Name;
}
public static String getCustomer_reference() {
return Customer_reference;
}
public static void setCustomer_reference(String customer_reference) {
Customer_reference = customer_reference;
}
public static String getPersoAppli() {
return PersoAppli;
}
public static void setPersoAppli(String persoAppli) {
PersoAppli = persoAppli;
}
public static String getGeneric_Ci() {
return Generic_Ci;
}
public static void setGeneric_Ci(String generic_Ci) {
Generic_Ci = generic_Ci;
}
public static String getCdfFile() {
return CdfFile;
}
public static void setCdfFile(String cdfFile) {
CdfFile = cdfFile;
}
public static String getPdflocation() {
return pdflocation;
}
public static void setPdflocation(String pdflocation) {
PdmData.pdflocation = pdflocation;
}
public String Cdffile(String reference) {
ServiceLocator locator = new ServiceLocator(); -------->Web Service Locator and call
try {
IService basicHttpBinding_IService = locator.getBasicHttpBinding_IService();
Result result = basicHttpBinding_IService.getFilebyDcode(reference);
//To download the files
String link = result.getLocation();
System.out.println(link);
File out = new File("C:\\TempDownload\\" + reference +".zip"); //Creating a zip file to store the contents of download file
new Thread(new Download(link,out)).start();
//To Unzip the file
Path source = Paths.get("C:\\TempDownload\\" + reference +".zip");
Path target = Paths.get("C:\\TempDownload\\Unzip");
try {
unzipFolder(source, target);
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
//Creating a File object for directory
File directoryPath = new File("C:\\TempDownload\\Unzip\\Pre Ppc" + reference + "A_Released");
//List of all files and directories
String[] contents = directoryPath.list();
System.out.println("List of files and directories in the specified directory:");
FilenameFilter pdffilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
String lowercaseName = name.toLowerCase();
if (lowercaseName.endsWith(".pdf")) {
return true;
} else {
return false;
}
}
};
String[] contents1 = directoryPath.list(pdffilter);
for(String fileName : contents1) {
System.out.println(fileName);
setCdfFile(fileName);
setPdflocation(directoryPath.toString());
}
//To extract the Data From PDF
File file = new File(getPdflocation() + "\\" + getCdfFile());
//FileInputStream fis = new FileInputStream(file);
PDDocument document = PDDocument.load(file);
PDFTextStripper pdfReader = new PDFTextStripper();
String docText = pdfReader.getText(document);
System.out.println(docText);
document.close();
//To extract details from document
String CI_Ref = "CI Ref";
int pos ;
pos = docText.indexOf(CI_Ref);
setGeneric_Ci(docText.substring(pos+7 , pos+15));
System.out.println("Generic CI: " + getGeneric_Ci());
//To get Details of CI
CustomerItem customerItem = basicHttpBinding_IService.getCiDetails(getGeneric_Ci());
setPersoAppli(customerItem.getPersoAppli());
setCode(customerItem.getCode());
setRevision(customerItem.getRevision());
setCustomer_Name(customerItem.getCustomerName());
setCustomer_reference(customerItem.getCustomerReference());
}catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Unable to reach Service : " + e.getMessage());
}
return getPersoAppli();
}
Module info file
module gload {
requires javafx.controls;
requires javafx.fxml;
requires java.desktop;
requires java.rmi;
requires java.base;
requires axis;
requires jaxrpc;
requires org.apache.pdfbox;
opens gload;
opens gload.views.main;
opens gload.utils;
opens gload.model;
opens gload.controllers;
opens org.tempuri;
opens org.datacontract.schemas._2004._07.PE_PPER_MyPdmWebServiceClient_Data;
}
and IF I keep Jaxrpc in classpath instead of module path I get error like this Description
The type javax.xml.rpc.ServiceException cannot be resolved. It is indirectly referenced from required .class files
OK, this won't really be an answer, more pointers to related issues and potential approaches to come up with solutions. But I'll post it as an answer as it is likely better to do that than lots of comments.
Unfortunately, you have multiple errors and issues, so I'll try to deal with some of them seperately.
According to:
Java FX Modular Application, Module not found (Java 11, Intellij)
The error:
Error occurred during initialization of boot layer
java.lang.module.FindException:
Module X not found, required by Y
can occur when --module-path is wrong and the module can't be found. Probably, that is at least one of your issues. The linked answer is for Idea and I don't use Eclipse, so I don't know how to resolve the issue in Eclipse, but perhaps you could do some research to find out.
Regarding:
The package javax.xml.namespace is accessible from more than one module
there is some info on what is going on here:
Eclipse is confused by imports ("accessible from more than one module").
This fix appears tricky to me. Please review the linked questions and solutions. It looks like either you need to either
Forego Java 9+ modularity OR
Manage your dependencies to not include the violating transitive dependency OR
Change to a library that doesn't rely on the broken library (probably the preferred solution in this case).
The broken library causing this issue is likely the version of jaxrpc you are using. My guess is that some of the relevant XML libraries were only added to standard Java in Java 9, but the jaxrpc library you are using was developed prior to that. So, jaxrpc either includes the XML libraries in its classes or makes use of a transitive library that does the same. This causes a conflict because the XML libraries can only be included once in the project.
Further info on your issues is in this answer:
Eclipse can't find XML related classes after switching build path to JDK 10
The info is so ugly . . . you could read the answer, it may either help or discourage you.
Some things you could do to help resolve the situation
What should be done about this is kind of tricky and will depend on your skill level and how or if you can solve it. I'll offer up some advice on some things you could do, but there are other options. You know your application better than I so you may be able to come up with better solutions for your application.
I'd advise separating these things out, just as a way of troubleshooting, get a project which works with all of the JavaFX components and one which works with all of the SOAP components and make sure they build and do what you want. Then try to combine the two projects either by integrating them into one project or running them in separate VMs with communication between the two (e.g. via an added REST API, though that is a much more complicated solution, so think hard about that before attempting it).
Also, upgrade to the latest version of JavaFX. I don't think it will fix your issue, but it can't hurt and it is possible some refinements in recent JavaFX versions may have done some things which might help ease some of your issues (though not all of them, as some of your issues stem from jaxrpc usage in a modular project, which is unrelated to JavaFX).
Also, and probably more importantly, consider using a different SOAP client framework that interacts better with modular Java 9+ than the broken implementation that jaxrpc appears to have.
In terms of whether you should make your application modular or not (include a module-info or not), I don't really know the best approach for you. Certainly, whichever way you choose you will run into issues. But, the issues and how to resolve them will be different depending on the chosen solution path (as I guess you have already discovered during the course of your investigation for the question).
If necessary, isolate the issues down to single separate issues. If you need help in resolving each separate issue post new questions that feature minimal reproducible example code to replicate the issue. Mind if you do so, that the code is absolutely minimal and also complete so that it replicates and asks about only one issue, not a combination of more than one and that the questions are appropriate tagged - e.g. if the question is about jaxrpc and modularity it should include jaxrpc and modular tags and no JavaFX code or tags (and vice versa) and certainly on pdf code or dependencies anywhere if that isn't part of the problem.
Test won't run correctly trying to run a JUnit test errors
package picocli;
import picocli.CommandLine.Option;
public class ComparatorRunnerConfig {
#Option(names = {"-rc", "--report-class"}, required = false,
description = "define report")
private String report;
public String getReport() {
return report;
}
}
My JUnit test:
package picocli;
import static org.junit.Assert.*;
import org.junit.Test;
public class ConfigurationTest {
#Test
public void testBasicConfigOptions() {
String args = "-rc BlahBlah";
ComparatorRunnerConfig mfc = new ComparatorRunnerConfig();
new CommandLine(mfc).parse(args);
String myTestValue = mfc.getReport();
assertEquals(myTestValue, "BlahBlah");
}
}
Test fails.
The problem is that the test has a subtle bug: the intention is to pass two arguments: the option "-rc" and its option parameter "BlahBlah", but what the test actually does is pass a single argument "-rc BlahBlah" with an embedded space.
Picocli will not be able to match this input and will throw an exception (probably the error message says something like “unknown option -rc BlahBlah”, but I’m away from my pc now, so cannot verify).
The solution is to change the test to either this:
String[] args = "-rc BlahBlah".split(" ");
or this:
String[] args = new String[] {"-rc", "BlahBlah"};
This bug in the test is actually a fairly common mistake and I’ve made this mistake myself a few times. :-)
As a side-note: you can use picocli’s tracing feature to help with troubleshooting issues like this, by setting system property -Dpicocli.trace=DEBUG.
I'm using Intellij IDEA IDE.
I wrote 2 java classes and 1 feature cucumber file in project. feature structure is:
Feature: First test
with Cucumber
Scenario: Testing
Given file.xml from ext
When take project path
Then run test
Also I wrote 1 jUnit java class for RunTest with Cucumber.class:
import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;
import org.hamcrest.SelfDescribing;
import gherkin.util.FixJava;
import cucumber.deps.com.thoughtworks.xstream.converters.ConverterRegistry;
#RunWith(Cucumber.class)
public class RunTest {
}
And this is signature of my Test class with cucumber's given, when and then:
public class CallSoapSteps {
//variables for file and path to project
String fileXML = "";
String pathToProj = "";
//take any xml file for insert it into Insert() SoapUI step
#Given("^file.xml from ext$")
public String file_xml_from_ext()
{
//take file
return fileXML = "path_to_xml_file";
}
//any statement about our xml file
#When("^take project path$")
public String take_project_path()
{
//take path to project
return pathToProj = "path_to_soap_project";
}
//any properties for our steps and running SoapTest
#Then("^run test$")
public void run_test() throws Exception {
//add test project
WsdlProject project = new WsdlProject(take_project_path());
//add xml file for test into property
project.setPropertyValue("File", file_xml_from_ext());
//get TestSuite and TestCase by name
TestSuite testSuite = project.getTestSuiteByName("Test");
TestCase testCase = testSuite.getTestCaseByName("Test");
//run test
testCase.run(new PropertiesMap(), false);
}
}
But if I try run jUnit Test, I catched this exception:
java.lang.NoSuchMethodError: gherkin.formatter.model.Scenario.getId()Ljava/lang/String;
And I don't know in which reasons I see this exception.
Also I see this before exception:
0 Scenarios
0 Steps
0m0.000s
As I know, Ljava/lang/String cheked if I string arrays as strings. But in this code I haven't arrays.
UPDATE.
So, I find reason for this exception.
Need to use gherkin 2.12.2.
In the Exception you provided above java.lang.NoSuchMethodError: gherkin.formatter.model.Scenario.getId()Ljava/lang/String;
i think you are using gherkin 2.12.0.jar which does not have getId function in the specified class
Please use gherkin 2.12.2.jar and place this jar in your project build path and try executing
Somewhat of a followup to How to use public class frome .java file in other processing tabs?; using the example from Usage class from .java file - is there a full doc for that? - Processing 2.x and 3.x Forum, I have this:
/tmp/Sketch/Sketch.pde
// forum.processing.org/two/discussion/3677/
// usage-class-from-java-file-is-there-a-full-doc-for-that
Foo tester;
void setup() {
size(600, 400, JAVA2D);
smooth(4);
noLoop();
clear();
rectMode(Foo.MODE);
fill(#0080FF);
stroke(#FF0000);
strokeWeight(3);
tester = new Foo(this);
tester.drawBox();
}
/tmp/Sketch/Foo.java
import java.io.Serializable;
//import peasy.org.apache.commons.math.geometry.Rotation;
//import peasy.org.apache.commons.math.geometry.Vector3D;
import processing.core.PApplet;
import processing.core.PGraphics;
public class Foo implements Serializable {
static final int GAP = 15;
static final int MODE = PApplet.CORNER;
final PApplet p;
Foo(PApplet pa) {
p = pa;
}
void drawBox() {
p.rect(GAP, GAP, p.width - GAP*2, p.height - GAP*2);
}
}
The example runs fine as is - but if I uncomment the import peasy.org... lines, then compilation fails with:
The package "peasy" does not exist. You might be missing a library.
Libraries must be installed in a folder named 'libraries' inside the 'sketchbook' folder.
Of course, I do have PeasyCam installed, under /path/to/processing-2.1.1/modes/java/libraries/peasycam/ - and it works fine, if I do a import peasy.*; from a .pde sketch.
I guess, this has something to do with paths - apparently pure Java files in a sketch, do not refer to the same library paths as .pde files in a sketch.
Is it possible to get this sketch to compile with the import peasy.org... lines (other than, I guess, copying/symlinking the peasycam library in the sketch folder, here /tmp/Sketch/ <--- EDIT: just tried symlinking as described, it doesn't work; the same error is reported)?
This is where you learn that Processing isn't actually Java, it just has a similar(ish) syntax and can run its code in the JVM by aggregating all .pde files into a single class that can be compiled for running on the JVM. Processing has its own rules for dealing with imports and the like.
Why not just do this entirely in Processing instead?
class Foo {
static int MODE = ...;
static int GAP = ...;
PApplet sketch;
public Foo(PApplet _sketch) {
sketch = _sketch;
...
}
void drawBox() {
sketch.rect(GAP, GAP, p.width - GAP*2, p.height - GAP*2);
}
...
}
and then make sure to have that in a file Foo.pde or something in the same dir as your sketch, with your sketch loading in the peasy library through the regular Processing import mechanism?
Ok, thanks to #MikePomaxKamermans answer, especially "by aggregating all .pde files into a single class", I simply tried importing peasy in the .pde file before the first reference to foo; that is, in /tmp/Sketch/Sketch.pde I now have:
// forum.processing.org/two/discussion/3677/
// usage-class-from-java-file-is-there-a-full-doc-for-that
import peasy.*; // add this
Foo tester;
...
... and then the sketch compiles without a problem (but note: while this approach works for this example, it somehow didn't work in the original problem that drove me to post the question).
Expected and actual values are same but the test result is failure in JUnit test. I don't know why this happens. Codes and result image are attached. One more weird thing is that there are error marks in the packages even though the source codes do not have any errors. An image about this is also attached). I guess two things are related each other. How can I solve this problem? Thanks.If you need more information, please ask me.
package tests;
import junit.framework.TestCase;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import net.n3.nanoxml.*;
public class NanoSetAttr3_wy_v1Tests extends TestCase {
public void test0() throws Exception {
//setattr3.out
String result;
ByteArrayOutputStream byteBuffer;
byteBuffer = new ByteArrayOutputStream();
System.setOut(new PrintStream(byteBuffer));
try{
SetAttr3_wy_v1.main(new String[] {});
}catch (Throwable t) {
t.printStackTrace(System.out);
}
result = new String(byteBuffer.toByteArray());
assertEquals(result, "<FOO Weight=\"80\"/>");
}
}
If you look closely at the Expected and Actual windows, you'll see that Expected has two lines and Actual has one. This means that the Expected output has a newline but the Actual output does not.
Regarding the error marks, open up Problems window for details (if you're not using Eclipse, there should be something similar).