Before you flag this as a duplicate, please note that I have read several other similar questions, but none of them fixed the issue.
I have an Eclipse project using maven. It uses Java 15, with Javafx 13.
When I try to run the app, it has the error message:
Error: Could not find or load main class app.cleancode.Start
I have tried:
refreshing the project,
rebuilding from the maven project,
and even deleting all of the eclipse files and reimporting the project.
None of them made any difference.
I can run any other project in Eclipse, but this one is just not working.
I am doing this on Windows 10 home.
My pom file:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>app.cleancode</groupId>
<artifactId>javafx-app</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>15</java.version>
<javafx.version>13</javafx.version>
</properties>
<dependencies>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-media</artifactId>
<version>${javafx.version}</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>${javafx.version}</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-swing</artifactId>
<version>${javafx.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<release>${java.version}</release>
<source>${java.version}</source>
<target>${java.version}</target>
<compilerArgs>--enable-preview</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.openjfx</groupId>
<artifactId>javafx-maven-plugin</artifactId>
<version>0.0.3</version>
<configuration>
<mainClass>app.cleancode.Start</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
app.cleancode.Start:
package app.cleancode;
import app.cleancode.game.GameListener;
import app.cleancode.game.GameLoop;
import app.cleancode.game.GameObject;
import app.cleancode.game.PhysicalLaw;
import app.cleancode.game.physics.Gravity;
import app.cleancode.game.physics.Movement;
import javafx.application.Application;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.input.KeyCombination;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class Start extends Application {
private static GameListener[] gameListeners = new GameListener[] {
};
#SuppressWarnings("unchecked")
private static GameObject<Node> [] gameObjects = new GameObject[] {
};
private static PhysicalLaw[] laws = new PhysicalLaw[] {
new Movement(),
new Gravity()
};
public static void main(String[] args) {
launch(args);
}
private Pane nodes = new Pane();
private Pane gamePane = new Pane();
#Override
public void start(Stage primaryStage) throws Exception {
Scene scene = new Scene(gamePane);
scene.getStylesheets().add("/app/cleancode/app.css");
nodes.getChildren().add(new Text("Loading"));
primaryStage.setTitle("Game");
primaryStage.setFullScreen(true);
primaryStage.setFullScreenExitKeyCombination(KeyCombination.NO_MATCH);
primaryStage.setScene(new Scene(nodes));
primaryStage.show();
for(GameListener listener : gameListeners) {
for(String gameObjectName : listener.getGameObjects()) {
for(GameObject<Node> gameObject : gameObjects) {
gameObject.addNode = this::addNode;
if(gameObject.getName().equalsIgnoreCase(gameObjectName)) {
try {
var gameObjectField = listener.getClass().getDeclaredField(gameObjectName);
gameObjectField.set(listener, gameObject);
break;
}catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
listener.startup();
}
scene.setFill(Color.BLACK);
primaryStage.setScene(scene);
primaryStage.setFullScreen(true);
GameLoop loop = new GameLoop(this::tick);
loop.start();
}
public void tick() {
for(GameListener gameListener : gameListeners) {
gameListener.update();
}
for(PhysicalLaw law : laws) {
for(GameObject<Node> gameObject : gameObjects) {
law.handle(gameObject);
}
}
}
public void addNode(Node node) {
gamePane.getChildren().add(node);
}
}
** module-info.java **:
module app.cleancode.javafx-app {
exports app.cleancode.axis;
exports app.cleancode.animation;
exports app.cleancode;
exports app.cleancode.sound;
exports app.cleancode.game.physics;
exports app.cleancode.bounds;
exports app.cleancode.game.snake;
exports app.cleancode.map;
exports app.cleancode.sprite;
exports app.cleancode.game;
requires java.desktop;
requires javafx.base;
requires javafx.graphics;
requires javafx.media;
requires javafx.swing;
}
Another piece of information I just found out is that if i create a new Start.java with just a main method, it works fine. Not sure why.
To answer my own question, the easiest solution is to create a new main class that calls the main of the original start.
First, rename Start.java to Starter.java (or whatever you want to call it)
finally, create a new Start.java in the place of the old one:
Start.java:
package app.cleancode;
public class Start {
public static void main(String[] args) {
Starter.main(args);
}
}
Then you can just run the new Start.java.
Related
I am trying to define a simple annotation and use it during compile time only to add a simple method to the consumed source file/class file but nothing is getting added.
I am using maven and java 1.8.
Below is the code and not sure where it is going wrong
Annotation class definition:
package com.test.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
#Target(ElementType.TYPE)
#Retention(RetentionPolicy.SOURCE)
public #interface AddMethod {
}
Processor for the annotation
package com.test.annotations;
import com.google.auto.service.AutoService;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.util.ElementFilter;
import javax.tools.JavaFileObject;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.util.stream.Collectors;
#SupportedAnnotationTypes("com.test.annotations.AddMethod")
#SupportedSourceVersion(SourceVersion.RELEASE_8)
#AutoService(Processor.class)
public class AddMethodProcessor extends AbstractProcessor {
#Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
// get all the classes annotated with ToJsonString class
Collection<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(AddMethod.class);
annotatedElements.forEach(e -> {
// some code to get the class name
try {
writeBuilderFile(qualifiedClassName);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
});
return true;
}
private void writeBuilderFile(String qualifiedClassName) throws IOException {
String packageName = null;
int lastDot = qualifiedClassName.lastIndexOf('.');
if (lastDot > 0) {
packageName = qualifiedClassName.substring(0, lastDot);
}
String simpleClassName = qualifiedClassName.substring(lastDot + 1);
JavaFileObject generatedSourceFile = processingEnv.getFiler()
.createSourceFile(qualifiedClassName);
try (PrintWriter out = new PrintWriter(generatedSourceFile.openWriter())) {
if (packageName != null) {
out.print("package ");
out.print(packageName);
out.println(";");
out.println();
}
out.print("public class ");
out.print(simpleClassName);
out.println(" {");
out.println();
out.print(" public ");
out.print("String");
out.println(" testMethod() {");
out.println(" return \"this is a test method\" ");
out.println(" }");
out.println();
out.println("}");
}
}
}
After this, I am running mvn install to install the jar in my .m2 repository so that the consumer can use it.
consumer project:
pom.xml
<dependencies>
<dependency>
<groupId>com.test</groupId>
<artifactId>add-method</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
<forceJavacCompilerUse>true</forceJavacCompilerUse>
<generatedSourcesDirectory>${project.build.directory}
/generated-sources/</generatedSourcesDirectory>
<annotationProcessors>
<annotationProcessor>
com.test.annotations.AddMethodProcessor
</annotationProcessor>
</annotationProcessors>
</configuration>
</plugin>
</plugins>
</build>
</project>
Test class using the annotation
package org.example;
import com.test.annotations.AddMethod;
#AddMethod
public class Test {
private String x;
}
On running build in intellij, I could not see the source file or class file having the auto generated method.
I'm doing a project managed with Maven. The purpose of the project is to access a .csv file and read specific columns from it. I have just started, but run into trouble with the ClassLoader.getSystemResources(String name) method which cannot find the resource specified with the name argument. I put the .csv file in a the Maven project's resources directory.
I think the problem is caused by using Maven to manage the project because I tested the ClassLoader.getSystemResources(String name) method in a test program with a working result. I've also tried using other methods to obtain the path of the `.csv' file in my project, but got the same failing result.
Please help me find out what has gone wrong and how to resolve the problem.
Thank you for your help!
The Error message:
[WARNING]
java.lang.NullPointerException: Cannot invoke "java.net.URL.toURI()" because the return value of "java.lang.ClassLoader.getSystemResource(String)" is null
at com.wordbankbuilder.NamedColumnBean.getNamedColumnBean (WordbankBuilder.java:80)
at com.wordbankbuilder.WordbankBuilder.main (WordbankBuilder.java:23)
at org.codehaus.mojo.exec.ExecJavaMojo$1.run (ExecJavaMojo.java:254)
at java.lang.Thread.run (Thread.java:832)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.879 s
[INFO] Finished at: 2021-10-04T11:52:03+11:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:3.0.0:java (default-cli) on project WordbankBuilder: An exception occured while executing the Java class. Cannot invoke "java.net.URL.toURI()" because the return value of "java.lang.ClassLoader.getSystemResource(String)" is null -> [Help 1]
[ERROR]
The code and POM file are as follows:
The main class - WordbankBuilder:
package com.wordbankbuilder;
import java.io.Reader;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import com.opencsv.*;
import com.opencsv.bean.*;
public class WordbankBuilder {
public static void main(String[] args) {
NamedColumnBean ncb = new NamedColumnBean();
ncb.getNamedColumnBean();
System.out.println("SUCCESS!");
}
}
class CsvBean {}
class NamedColumnBean extends CsvBean {
#CsvBindByName(column = "word")
private String name;
#CsvBindByName(column = "phonetic")
private String phonetic;
#CsvBindByName(column = "translation")
private String translation;
public String getName () {
return this.name;
}
public String getPhonetic () {
return this.phonetic;
}
public String getTranslation () {
return this.translation;
}
public void setName(String name) {
this.name = name;
}
public void setPhonetic(String phonetic) {
this.phonetic = phonetic;
}
public void setTranslation(String translation) {
this.translation = translation;
}
public List<CsvBean> namedColumnBeanBuilder (Path path, Class clazz) {
// read and parse ecdict.mini.csv
CsvTransfer csvTransfer = new CsvTransfer();
ColumnPositionMappingStrategy ms = new ColumnPositionMappingStrategy();
ms.setType(clazz);
try (Reader reader = Files.newBufferedReader(path)) {
CsvToBean cb = new CsvToBeanBuilder(reader).withType(clazz).withMappingStrategy(ms).build();
csvTransfer.setCsvList(cb.parse());
} catch (IOException ioEx) {
ioEx.printStackTrace();
}
return csvTransfer.getCsvList();
}
public List<CsvBean> getNamedColumnBean () {
Path path = null;
try {
URI resURI = ClassLoader.getSystemResource("/src/main/resources/ecdict.mini.csv").toURI();
path = Paths.get(resURI);
path = Paths.get("ecdict.mini.csv");
} catch (URISyntaxException uriEx) {
uriEx.printStackTrace();
System.exit(1);
}
return namedColumnBeanBuilder(path, NamedColumnBean.class);
}
}
The CsvTransfer class - CsvTransfer.java
package com.wordbankbuilder;
import java.util.ArrayList;
import java.util.List;
public class CsvTransfer {
private List<String[]> csvStringList;
private List<CsvBean> csvList;
public CsvTransfer() {}
public List<String[]> getCsvStringList() {
if (csvStringList != null) return csvStringList;
return new ArrayList<String[]>();
}
public void addLine(String[] line) {
if (this.csvList == null) this.csvStringList = new ArrayList<>();
this.csvStringList.add(line);
}
public void setCsvStringList(List<String[]> csvStringList) {
this.csvStringList = csvStringList;
}
public void setCsvList(List<CsvBean> csvList) {
this.csvList = csvList;
}
public List<CsvBean> getCsvList() {
if (csvList != null) return csvList;
return new ArrayList<CsvBean>();
}
}
The POM.xml file:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wordbankbuilder</groupId>
<artifactId>WordbankBuilder</artifactId>
<version>1.0.0</version>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<mainClass>com.wordbankbuilder.WordbankBuilder</mainClass>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources/</directory>
</resource>
</resources>
</build>
<dependencies>
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>4.1</version>
</dependency>
</dependencies>
</project>
I am attempting to migrate an AspectJ project to a Byte Buddy plugin and having some difficulty. I want to do compile-time byte code modifications.
The exception I am getting is :
[ERROR] Failed to execute goal net.bytebuddy:byte-buddy-maven-plugin:1.11.0:transform (default) on project timing-example: Failed to transform class files in /tmp/timing-example/target/classes: protected void com.walterjwhite.examples.timing.TimingExampleCommandLineHandler.doRun(java.lang.String[]) does not define an index 1 -> [Help 1]
Plugin:
NOTE:
package com.walterjwhite.timing.plugin;
import static net.bytebuddy.matcher.ElementMatchers.*;
import com.walterjwhite.timing.annotation.Timing;
import java.io.IOException;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.build.HashCodeAndEqualsPlugin;
import net.bytebuddy.build.Plugin;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.ClassFileLocator;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.matcher.ElementMatchers;
#HashCodeAndEqualsPlugin.Enhance
public class TimingPlugin extends Plugin.ForElementMatcher implements Plugin.Factory {
public TimeoutPlugin() {
super(declaresMethod(isAnnotatedWith(Timing.class)));
}
#Override
public DynamicType.Builder<?> apply(
DynamicType.Builder<?> builder,
TypeDescription typeDescription,
ClassFileLocator classFileLocator) {
System.out.println("Timing: start");
for (MethodDescription.InDefinedShape methodDescription :
typeDescription
.getDeclaredMethods()
.filter(
not(isBridge()).<MethodDescription>and(isAnnotatedWith(Timing.class)))) {
System.out.println("Timing: " + methodDescription);
if (methodDescription.isAbstract()) {
throw new IllegalStateException(
"Cannot implement timing on an abstract method: " + methodDescription);
}
builder = builder.visit(Advice.to(TimingAdvice.class).on(is(methodDescription)));
}
System.out.println("Timing: end");
return builder;
}
Advice:
NOTE: I would like to wrap the original method invocation in a try-catch-finally so I can time it. I'm not sure I can do that with advice. In any case, that is further down the road, I want to see that I can write a plugin and have my code instrumented.
package com.walterjwhite.timing.plugin;
import java.lang.reflect.Method;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.implementation.bind.annotation.AllArguments;
import net.bytebuddy.implementation.bind.annotation.Origin;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
public class TimingAdvice {
#RuntimeType
#Advice.OnMethodEnter
public static void onEnter(#Advice.This Object intercepted, #Origin Method method, #RuntimeType #AllArguments Object[] arguments)
throws Throwable {
System.out.println(System.currentTimeNanos());
}
}
Method being advised:
#Timing
#Override
protected void doRun(String... arguments) {
int i = 0;
while (true) {
try {
System.out.println("i:" + i++);
Thread.sleep(50);
} catch (InterruptedException e) {
System.out.println("Exiting as instructed to do so.");
System.exit(1);
}
}
}
excerpt from pom.xml:
<plugin>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy-maven-plugin</artifactId>
<version>1.11.0</version>
<executions>
<execution>
<goals>
<goal>transform</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>com.walterjwhite.aspects.timing</groupId>
<artifactId>plugin</artifactId>
<version>0.0.1</version>
</dependency>
</dependencies>
</plugin>
Lastly, the plugin project has the file in place because the byte buddy plugin does pick it up. But, whenever it attempts to transform the class files, it fails. So, my configuration isn't quite right.
EDIT #2:
The pom is partially correct, the other issue I ran into was:
NoClassDefFoundError
This was due to the fact that I needed the dependency also listed as a dependency for the project and not just the plugin. Ie:
<plugin>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy-maven-plugin</artifactId>
<version>1.11.0</version>
<executions>
<execution>
<goals>
<goal>transform</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>com.walterjwhite.aspects.timing</groupId>
<artifactId>plugin</artifactId>
<version>0.0.1</version>
</dependency>
</dependencies>
</plugin>
</plugins
</build>
<dependencies>
<dependency>
<groupId>com.walterjwhite.aspects.timing</groupId>
<artifactId>plugin</artifactId>
<version>0.0.1</version>
</dependency>
</dependencies>
...
You are blending annotations from the MethodDelegation API with the Advice API. The annotations are very similar as they intend to support the same approach but an unfortunate side effect is that they get confused. Instead of importing
import net.bytebuddy.implementation.bind.annotation.AllArguments;
import net.bytebuddy.implementation.bind.annotation.Origin;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
you need to use annotations declared within the Advice class with the same name. Ideally, you prefix all annotations with Advice:
#Advice.OnMethodEnter
public static void onEnter(#Advice.This Object intercepted, #Advice.Origin Method method, #Advice.AllArguments Object[] arguments)
throws Throwable {
System.out.println(System.currentTimeNanos());
}
Note that the #RuntimeType has no equivalent in the Advice API. It is not normally needed.
package org.example;
import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.updatesreceivers.DefaultBotSession;
public class App {
public static void main( String[] args ) {
try {
TelegramBotsApi botsApi = new TelegramBotsApi(DefaultBotSession.class);
botsApi.registerBot(new s261251Bot());
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
package org.example;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
public class s261251Bot extends TelegramLongPollingBot {
#Override
public String getBotUsername() {
return "username";
}
#Override
public String getBotToken() {
return "..............";
}
#Override
public void onUpdateReceived(Update update) {
SendMessage message = new SendMessage();
message.setChatId(String.valueOf((update.getMessage().getChatId())));
message.setText("hello " + update.getMessage().getFrom().getFirstName() +" " + "\nInsert your matric number." + update.getMessage().getText());
try {
execute(message);
}catch (TelegramApiException e){
e.printStackTrace();
}
}
}
I put the right username and token but in here I replace it with other
I keep getting this error:
C:\Users\safwa\Documents\IntelliJ\assignment-2-safwan0908\src\main\java\my\assignment2\src\main\java\org\example\s261251Bot.java:9:8
java: cannot access java.util.concurrent.CompletableFuture class
file for java.util.concurrent.CompletableFuture not found
I had the same problem.
Make sure you use the correct or the same java version in your project and frameworks.
For more details read this article
In my case, I updated my maven version, using these properties (as described in the article):
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
or
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>LATEST</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
</plugins>
</build>
I am a beginner in Cucumber and i have written a basic tests for login and going to the homepage using in a maven project. I suspect there is some consistency issue with POM.xml.
Please find below the files
I have tried with multiple combinations for the dependencies in pom file but seems the issue persists.
1) stepdefination file
package StepDefinition;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
public class loginStepDefinition {
WebDriver driver;
#Given("^User is already on login page$")
public void user_already_on_login_page(){
System.setProperty("webdriver.chrome.driver","/Users/nilesh.gupta/Desktop/chromedriver" );
driver = new ChromeDriver();
driver.get("https://classic.crmpro.com");
}
#When("^Tittle of login page is Free CRM$")
public void tittle_login_page_is_Free_CRM() {
String tittle = driver.getTitle();
System.out.println("tittle is : " + tittle);
Assert.assertEquals("#1 Free CRM for Any Business: Online Customer Relationship Software", tittle);
}
#Then("^User enters username and password$")
public void user_enters_username_and_password() {
driver.findElement(By.xpath("/html/body/div[2]/div/div[3]/form/div/input[1]\n" )).sendKeys("naveenk");
driver.findElement(By.xpath("/html/body/div[2]/div/div[3]/form/div/input[2]\n" )).sendKeys("test#123");
}
#Then("^User clicks on login button$")
public void user_clicks_on_login_button() {
driver.findElement(By.className("btn btn-small")).click();
}
#Then("^User is on Home Page$")
public void user_is_on_Home_Page() {
String tittle= driver.getTitle();
System.out.println("tittle is : " + tittle );
Assert.assertEquals("CRMPRO", tittle);
}
}
login.feature
Feature: Free CRM Login Feature
Scenario: Free CRM Login Test Scenario
Given User is already on login page
When Tittle of login page is Free CRM
Then User enters username and password
Then User clicks on login button
Then User is on Home Page
testrunner.java
package MyRunner;
import org.junit.runner.RunWith;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
#RunWith(Cucumber.class)
#CucumberOptions(
features = "/Users/nilesh.gupta/eclipse-workspace/CucumberBDD/src/main/java/Features/login.feature",
glue={"stepDefinition"}
/*format={"pretty","html:test-output"}*/
)
public class testRunner {
}
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>CucumberBDD</groupId>
<artifactId>CucumberBDD</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>CucumberBDD</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<cucumber.version>4.8.0</cucumber.version>
<selenium.version>3.5.3</selenium.version>
</properties>
<dependencies>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-junit</artifactId>
<version>${cucumber.version}</version>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>${cucumber.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>${selenium.version}</version>
</dependency>
</dependencies>
</project>
Output
There were undefined steps. You can implement missing steps with the snippets below:
#Given("User is already on login page")
public void user_is_already_on_login_page() {
// Write code here that turns the phrase above into concrete actions
throw new cucumber.api.PendingException();
}
#When("Tittle of login page is Free CRM")
public void tittle_of_login_page_is_Free_CRM() {
// Write code here that turns the phrase above into concrete actions
throw new cucumber.api.PendingException();
}
#Then("User enters username and password")
public void user_enters_username_and_password() {
// Write code here that turns the phrase above into concrete actions
throw new cucumber.api.PendingException();
}
#Then("User clicks on login button")
public void user_clicks_on_login_button() {
// Write code here that turns the phrase above into concrete actions
throw new cucumber.api.PendingException();
}
#Then("User is on Home Page")
public void user_is_on_Home_Page() {
// Write code here that turns the phrase above into concrete actions
throw new cucumber.api.PendingException();
}
Please try to make habit to write testing code in the test folder src/test/java instead of main . Everything that write into src/main/java is per default packaged and deliver to your customer whereas everything that you put into src/test/java is no.
Features Options helps Cucumber to locate the Feature file in the project folder structure.
if the Feature file is in the deep folder structure then please use features = “src/test/features“.
Glue
use to locate the Step Definition file.
Once you make changes then please refer below code for your runner file.
package MyRunner;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
#CucumberOptions(
features = "src/test/features"
,glue={"src/test/stepDefinition"}
,monochrome = false
)
public class testRunner {
}
Try, replace your code in Runner with this. Rebuild project and close and reopen it.
package MyRunner;
import org.junit.runner.RunWith;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
#RunWith(Cucumber.class)
#CucumberOptions(
features = "src/main/java/Features/login.feature",
glue={"StepDefinition"}
/*format={"pretty","html:test-output"}*/
)
public class testRunner {
}
In your example, I think the actual problem is that you cannot use anchors ^ or $ in your stepdefinitions' (Cucumber Expressions) and it shouldn't be there for newer version of io.cucumber. That style is used for info.cukes version.
It should be
#Given("User is already on login page")
public void user_already_on_login_page(){
System.setProperty("webdriver.chrome.driver","/Users/nilesh.gupta/Desktop/chromedriver" );
driver = new ChromeDriver();
driver.get("https://classic.crmpro.com");
}
Instead of
#Given("^User is already on login page$")
public void user_already_on_login_page(){
System.setProperty("webdriver.chrome.driver","/Users/nilesh.gupta/Desktop/chromedriver" );
driver = new ChromeDriver();
driver.get("https://classic.crmpro.com");
}