Cucumber and Selenium Error on Feature - java

I created a automated test scenario using selenium + cucumber on java, and when I try to execute my test nothing occur. I don't know what I did worng but I think that something happend with my feature, because exist warning on the following messages "No definition found for I try to login on facebook", "No definition found for I put my user "email"", "No definition found for I put my password "pass"" and "No definition found for validate login".
I imported these jars using maven: cucumber-java : 1.2.5/cucumber-junit : 1.2.5/selenium-java : 3.0.1/selenium-firefox-driver : 3.0.1/junit : 4.12
RunTest.java
package com.tdd.facebook;
import org.junit.runner.RunWith;
import cucumber.api.junit.Cucumber;
import cucumber.api.CucumberOptions;
#RunWith(Cucumber.class)
#CucumberOptions(
format = {"pretty", "html:target/cucumber"},
features = {"src/test/resources"}
)
public class RunTest {
public RunTest() {
// TODO Auto-generated constructor stub
}
}
LoginSteps.java
package com.tdd.facebook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import cucumber.api.PendingException;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class LoginSteps {
WebDriver driver = null;
#Given("^I try to login on facebook$")
public void i_try_to_login_on_facebook() throws Throwable {
System.setProperty("webdriver.gecko.driver", "C:\\Caio\\Selenium\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.facebook.com/");
throw new PendingException();
}
#When("^I put my user \"([^\"]*)\"$")
public void i_put_my_user(String email) {
driver.findElement(By.id(email)).click();
driver.findElement(By.id(email)).sendKeys("UserTest");
}
#When("^I put my password \"([^\"]*)\"$")
public void i_put_my_password(String pass){
driver.findElement(By.id(pass)).click();
driver.findElement(By.id(pass)).sendKeys("Test");
}
#Then("^validate login$")
public void validate_login() throws Throwable {
System.out.println("Login OK");
}
public LoginSteps() {
// TODO Auto-generated constructor stub
}
}
Login.feature
Feature: Login on facebook
Scenario: Check if the login is successful
Given I try to login on facebook
When I put my user "email"
When I put my password "pass"
Then validate login
pow.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>com.tdd</groupId>
<artifactId>facebook</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>facebook</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-firefox-driver</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
</project>

You need to add glue option to cucumberoptions with the path to the step definition classes. Use glue="com.tdd.facebook". I am not sure about this but you might want to remove the constructor in the runner RunTest.
In the LoginStps class - i_try_to_login_on_facebook() method, you are declaring another driver variable and initializing it. Thus the driver field of the class will remain null. Remove this. Also in the same method you are throwing a k. As you have implemented the step you do not need it anymore.
Also do check if all the jars are imported in the pom. I think you are missing some jars. Check the cucumber java page.

Related

Undefined Step definitions in Cucumber Java

I added the login steps in Login class. But when I run the scenario from the Login.feature file I still get undefined steps error.
Login class
package stepDefinitions;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
public class Login {
#Given("I am on the login page")
public void ı_am_on_the_login_page() {
// Write code here that turns the phrase above into concrete actions
throw new io.cucumber.java.PendingException();
}
#When("I enter a correct e-mail address")
public void ı_enter_a_correct_e_mail_address() {
// Write code here that turns the phrase above into concrete actions
throw new io.cucumber.java.PendingException();
}
#And("I enter a correct password")
public void ı_enter_a_correct_password() {
// Write code here that turns the phrase above into concrete actions
throw new io.cucumber.java.PendingException();
}
#And("I click on login button")
public void ı_click_on_login_button() {
// Write code here that turns the phrase above into concrete actions
throw new io.cucumber.java.PendingException();
}
#Then("I should be presented with successful login message")
public void ı_should_be_presented_with_successful_login_message() {
// Write code here that turns the phrase above into concrete actions
throw new io.cucumber.java.PendingException();
}
}
This is my Login.feature file
Feature: Login page
Scenario: Successful login test
Given I am on the login page
When I enter a correct e-mail address
And I enter a correct password
And I click on login button
Then I should be presented with successful login message
pom.xml file
<?xml version="1.0" encoding="UTF-8"?>
<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>org.example</groupId>
<artifactId>Segmentify_Project</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.1.4</version>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>7.3.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-testng -->
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-testng</artifactId>
<version>7.3.3</version>
</dependency>
</dependencies>
</project>
This is the project format
enter image description here
I receive the following error when I run the scenario from Login.feature
Step undefined
You can implement this step and 4 other step(s) using the snippet(s) below:
#Given("I am on the login page")
public void ı_am_on_the_login_page() {
// Write code here that turns the phrase above into concrete actions
throw new io.cucumber.java.PendingException();
}
I got an error similar to this.
I tried different solution, like edit configuration. But when i create runner class and run it, the feature started working without any problem.
My runner class
#RunWith(Cucumber.class)
#CucumberOptions(features ="C:\\Users\\user1\\Desktop\\Selenium\\com.cucumber\\src\\test\\resources\\features"
,glue = "stepDefinition")
public class testRunner {
}

Facing error "cucumber.runtime.CucumberException: No backends were found."

I am working on Selenium with Cucumber setup and I am facing error when I run the TestRunner file.
cucumber.runtime.CucumberException: No backends were found. Please make sure you have a backend module on your CLASSPATH.
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>Automation</groupId>
<artifactId>Cucumber</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Cucumber</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-junit -->
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.2.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-java -->
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.2.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
</dependency>
</dependencies>
</project>
I have mapped feature file to StepDefinition file as shown below
Feature file
Feature: Login Functionality
Scenario: Home page default login
Given User is on Home page
When User logs into application with valid credentials
Then User should be logged into application and landing page should be displayed to user
StepDefinition file
package stepDefenition;
import org.junit.runner.RunWith;
import cucumber.api.junit.Cucumber;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.When;
import cucumber.api.java.en.Then;
#RunWith(Cucumber.class)
public class StepDefenition {
#Given("^User is on Home page$")
public void user_is_on_home_page() throws Throwable {
System.out.println("User is on Home Page");
}
#When("^User logs into application with valid credentials$")
public void user_logs_into_application_with_valid_credentials() throws Throwable {
System.out.println("User enters valid credentials and clicks on submit");
}
#Then("^User should be logged into application and landing page should be displayed to user$")
public void user_should_be_logged_into_application_and_landing_page_should_be_displayed_to_user() throws Throwable {
System.out.println("User logged in successfully and landing page is displayed to user with all the details");
}
}
Test Runner File:
package cucumberOption;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
#CucumberOptions(
features = "src/test/java/features",
glue="stepDefenition")
public class TestRunner {
}
I am using version:
Neon.3 Release (4.6.3) of Eclipse
Natural 0.7.6 Cucumber plugin
Maven version : Apache Maven 3.6.3
Java Version : java version "1.8.0_241"
structure of the project
I have tried changing versions for java and Junit and adding Io.cucumber dependencies nothing worked.
Added java 1.8 jdk to project build path.
I have viewed all previous threads on this kind of issue.
I did not understand why you using #RunWith annotation in step def class. As cucumber will automatically take care of running it via cucumberRunner, so you can execute your test either from Runner class or via feature files(Scenario level or entire feature file) w/o using any #RunWith annotation. Probably this is the cause of your error here-See below exception:
cucumber.runtime.CucumberException:
Classes annotated with #RunWith(Cucumber.class) must not define any
Step Definition or Hook methods. Their sole purpose is to serve as
an entry point for JUnit. Step Definitions and Hooks should be defined
in their own classes. This allows them to be reused across features.
Offending class: class com.abc.StepDefs.FWFeatureTestSteps (for ex).
Also you need not to have separate junit dependency in pom, only cucumber-junit is enough as long as you want cucumber to get the job done.
Note: Don't mix io.cucumber and info.cukes, use any of them. Mixing both will also cause this very same exception.

org.testng.TestNGException: Cannot instantiate cucumber test runner

hi guys im trying to run my cucumber framework using testng, im pretty sure im a version issue but id appreciate it if someone can point the problem here thanks
features:
Feature: Application Login
Scenario: Home page default login
Given user is on landing page
When user logins into the application with username "jon" and password
"1234"
Then Home page is displayed
And Cards displayed "true"
Scenario: Home page default login2
Given user is on landing page
When user logins into the application with username "john" and password
"4321"
Then Home page is displayed
And Cards displayed "false"
Definitions:
package StepDefinations;
import cucumber.api.PendingException;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.When;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.And;
public class LoginDefination {
#Given("^user is on landing page$")
public void user_is_on_landing_page() throws Throwable {
//code
System.out.println("on landing page");
}
#When("^user logins into the application with username and password$")
public void user_logins_into_the_application_with_username_and_password() throws Throwable {
//code
System.out.println("logging in");
}
#When("^user logins into the application with username \"([^\"]*)\" and password \"([^\"]*)\"$")
public void user_logins_into_the_application_with_something_and_password_something(String strArg1, String strArg2) throws Throwable {
System.out.println(strArg1 +" "+ strArg2);
}
#Then("^Home page is displayed$")
public void home_page_is_displayed() throws Throwable {
//code
System.out.println("hello homepage");
}
#And("^Cards are displayed$")
public void cards_are_displayed() throws Throwable {
//code
System.out.println("hello cards");
}
#And("^Cards are not displayed$")
public void cards_are_not_displayed() throws Throwable {
//code
System.out.println("hello not cards");
}
#And("^Cards displayed \"([^\"]*)\"$")
public void cards_displayed(String args) throws Throwable {
//code
System.out.println("this will or will not display the cards - " + args);
}
}
test runner file:
package CucumberOptions;
import cucumber.api.CucumberOptions;
import cucumber.api.testng.AbstractTestNGCucumberTests;
//Feature
#CucumberOptions(
features = "src\\test\\java\\features",
//if u want tp execute everything then just give the path till the package level
glue= "StepDefinations"//Package name
)
public class TestRunner extends AbstractTestNGCucumberTests {
}
testng xml file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test name="cucumber testing 101">
<classes>
<class name="CucumberOptions.testme"/>
<class name="CucumberOptions.TestRunner"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
maven 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>Cucumber</groupId>
<artifactId>Automation</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Automation</name>
<url>http://maven.apache.org</url>
<build>
<resources>
<resource>
<directory>src/main/java/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.0</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-java -->
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.2.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-testng -->
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-testng</artifactId>
<version>1.1.5</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.14.0</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.10</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
error:
[RemoteTestNG] detected TestNG version 6.10.0
org.testng.TestNGException:
Cannot instantiate class CucumberOptions.TestRunner
at org.testng.internal.ObjectFactoryImpl.newInstance(ObjectFactoryImpl.java:40)
at org.testng.internal.ClassHelper.createInstance1(ClassHelper.java:363)
at org.testng.internal.ClassHelper.createInstance(ClassHelper.java:275)
at org.testng.internal.ClassImpl.getDefaultInstance(ClassImpl.java:126)
at org.testng.internal.ClassImpl.getInstances(ClassImpl.java:191)
at org.testng.TestClass.getInstances(TestClass.java:100)
at org.testng.TestClass.initTestClassesAndInstances(TestClass.java:86)
at org.testng.TestClass.init(TestClass.java:78)
at org.testng.TestClass.<init>(TestClass.java:41)
at org.testng.TestRunner.initMethods(TestRunner.java:425)
at org.testng.TestRunner.init(TestRunner.java:252)
at org.testng.TestRunner.init(TestRunner.java:222)
at org.testng.TestRunner.<init>(TestRunner.java:171)
at org.testng.remote.support.RemoteTestNG6_10$1.newTestRunner(RemoteTestNG6_10.java:28)
at org.testng.remote.support.RemoteTestNG6_10$DelegatingTestRunnerFactory.newTestRunner(RemoteTestNG6_10.java:61)
at org.testng.SuiteRunner$ProxyTestRunnerFactory.newTestRunner(SuiteRunner.java:623)
at org.testng.SuiteRunner.init(SuiteRunner.java:189)
at org.testng.SuiteRunner.<init>(SuiteRunner.java:136)
at org.testng.TestNG.createSuiteRunner(TestNG.java:1375)
at org.testng.TestNG.createSuiteRunners(TestNG.java:1355)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1209)
at org.testng.TestNG.runSuites(TestNG.java:1133)
at org.testng.TestNG.run(TestNG.java:1104)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.testng.internal.ObjectFactoryImpl.newInstance(ObjectFactoryImpl.java:29)
... 25 more
Caused by: java.lang.NoSuchMethodError: cucumber.runtime.RuntimeOptionsFactory.<init>(Ljava/lang/Class;[Ljava/lang/Class;)V
at cucumber.api.testng.AbstractTestNGCucumberTests.<init>(AbstractTestNGCucumberTests.java:27)
at CucumberOptions.TestRunner.<init>(TestRunner.java:14)
... 30 more
its a simple piece of code but im just trying to make it work using testng then maven, if someone can help me out i will be very thankful :)
Incompatible versions of TestNG and Cucumber libraries. Validate the versions of them in your dependency tree and check what version of TestNG fits to the version of your Cucumber library, for example here:
https://mvnrepository.com/artifact/info.cukes/cucumber-testng
https://mvnrepository.com/artifact/io.cucumber/cucumber-testng
UPDATE: I noticed that you have actually posted your pom.xml
Update the version of cucumber-testng to 1.2.5 (use the same version as for cucumber-java). Use testng version 6.9.10 (if you do not mind). This way you will align all libraries versions.
CONFIRMED: You have a conflict between cucumber-testng ver. 1.1.5 and cucumber-java ver. 1.2.5. Set both libraries to either version 1.1.5, or update them to use version 1.2.5.

spring jpa - At least one JPA metamodel must be present*

Anybody know why it doesn't work?
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
06/04/2017 14:11:24.732 ERROR [main] - org.springframework.boot.SpringApplication: Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: At least one JPA metamodel must be present!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:742)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151)
at com.cadit.web.WebApplicationAware.main(WebApplicationAware.java:19)
Caused by: java.lang.IllegalArgumentException: At least one JPA metamodel must be present!
at org.springframework.util.Assert.notEmpty(Assert.java:277)
at org.springframework.data.jpa.mapping.JpaMetamodelMappingContext.<init>(JpaMetamodelMappingContext.java:52)
at org.springframework.data.jpa.repository.config.JpaMetamodelMappingContextFactoryBean.createInstance(JpaMetamodelMappingContextFactoryBean.java:71)
at org.springframework.data.jpa.repository.config.JpaMetamodelMappingContextFactoryBean.createInstance(JpaMetamodelMappingContextFactoryBean.java:26)
at org.springframework.beans.factory.config.AbstractFactoryBean.afterPropertiesSet(AbstractFactoryBean.java:134)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
... 16 common frames omitted
I defined entities in com.cadit.entities:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="TEST")
public class GenericBeans implements BeanType, IEntity<Long> {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "TEST_PAID")
protected Long id;
#Column(name = "SOCIETA")
private String SocietaCod;
#Column(name = "CONTO_INTERMEDIARIO")
private String contoInt;
#Column(name = "TIPO_OPERAZIONE")
private String tipoOpe;
public GenericBeans(String societaCod, String contoInt, String tipoOpe) {
SocietaCod = societaCod;
this.contoInt = contoInt;
this.tipoOpe = tipoOpe;
}
public GenericBeans() {
}
public String getSocietaCod() {
return SocietaCod;
}
public void setSocietaCod(String societaCod) {
SocietaCod = societaCod;
}
public String getContoInt() {
return contoInt;
}
public void setContoInt(String contoInt) {
this.contoInt = contoInt;
}
public String getTipoOpe() {
return tipoOpe;
}
public void setTipoOpe(String tipoOpe) {
this.tipoOpe = tipoOpe;
}
#Override
public String toString() {
return "CSV [SocietaCod=" + SocietaCod + ", contoInt=" + contoInt + ", tipoOpe=" + tipoOpe + "]";
}
#Override
public Long getId() {
return this.id;
}
#Override
public void setId(Long id) {
this.id=id;
}
}
I definied my datasource entry definition for spring:
import org.apache.log4j.Logger;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#ComponentScan
#EntityScan("com.cadit.entities")
//#EnableJpaRepositories("com.cadit.entities")
#EnableTransactionManagement
#PropertySource("classpath:db-config.properties")
public class DbAutoConfiguration {
static final Logger logger = Logger.getLogger(DbAutoConfiguration.class);
public DbAutoConfiguration() {
}
#Bean
#ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource(){
//DataSource ds =new EmbeddedDatabaseBuilder().addScript("classpath:sql/schema.sql").addScript("classpath:testdb/data.sql").build();
DataSourceBuilder ds = DataSourceBuilder.create();
logger.info("dataSource = " + ds);
return ds.build();
}
}
My db-config.properties is:
spring.jpa.hibernate.ddl-auto: validate
spring.jpa.hibernate.naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy
#spring.jpa.database: SQL
spring.jpa.show-sql: true
spring.datasource.driverClassName=net.sourceforge.jtds.jdbc.Driver
spring.datasource.url=jdbc:jtds:sqlserver://localhost:1433;databaseName=example
spring.datasource.username=xxx
spring.datasource.password=xxx
IEntity is:
public interface IEntity <I extends Serializable> extends Serializable{
/**
* Property rappresenta la primary key.
*/
String P_ID = "id";
/**
* restituisce la primary key
* #return
*/
I getId();
/**
* imposta la primary key
* #param id
*/
void setId(I id);
}
I try to write CSV file to database using CrudRepository interface of spring:
import java.io.File;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.repository.CrudRepository;
import com.cadit.entities.GenericBeans;
import com.csvreader.CsvReader;
public class CsvReaders {
static final Logger logger = Logger.getLogger(CsvReader.class);
#Autowired
public CrudRepository<GenericBeans,Long> _entitymanager;
public List loadDataFromCsv(String fileName) {
try {
File file = new ClassPathResource(fileName).getFile();
CsvReader csv = new CsvReader(file.getAbsoluteFile().getPath(),';');
csv.readHeaders();
List l = new LinkedList();
GenericBeans b = new GenericBeans ();
while (csv.readRecord())
{
b.setSocietaCod(csv.get(0));
b.setContoInt(csv.get(1));
b.setTipoOpe(csv.get(2));
_entitymanager.save(b); //persist on db
l.add(b);
b = new GenericBeans();
}
b=null;
return l;
} catch (Exception e) {
logger.error("Error occurred while loading object list from file " + fileName, e);
return Collections.emptyList();
}
}
}
I DO NOT use main class but a class which extend SpringBootServletInitializer because i want to run it on both standalone tomcat and Tomcat installation as WAR application
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
#ComponentScan(basePackages={"com.cadit.entities","com.cadit.beans"})
#EnableAutoConfiguration
public class WebApplicationAware extends SpringBootServletInitializer {
private static Class<WebApplicationAware> applicationClass = WebApplicationAware.class;
public static void main(String[] args) {
SpringApplication.run(applicationClass, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(applicationClass);
}
}
All properties file are in classpath resources because it's a maven project.
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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>org.springframework</groupId>
<artifactId>xxxx</artifactId>
<version>0.1.0</version>
<packaging>war</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.11.1.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0.2</version>
</dependency>
<!-- altre dipendenze non spring -->
<!-- https://mvnrepository.com/artifact/net.sourceforge.javacsv/javacsv -->
<dependency>
<groupId>net.sourceforge.javacsv</groupId>
<artifactId>javacsv</artifactId>
<version>2.0</version>
</dependency>
<!-- per jpa solo se si usa il Tomcat embedded -->
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<!-- end -->
<!-- dipendenze logback -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.7</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.1.7</version>
</dependency>
<!-- fine dip logback -->
</dependencies>
<properties>
<start-class>hello.WebApplicationAware</start-class>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
What's the problem, why doesn't it find JPA entities when I run WebApplicationAware class?
Spring does not find any JPA Entities, so no JPA Meta Model is created, that is why you face the exception.
The cause of this problem may be a wrong persistence-api version on your class path.
You are using
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0.2</version>
</dependency>
but I am pretty shure your spring version uses persistence-api version 2.
Could it be, you are using #Entity annotation from version 1 ?
At runtime spring uses version 2, and this is searching for Entites using #Entity from version 2 only !
Remove the dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.11.1.RELEASE</version>
</dependency>
Instead add
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
This will give you all JPA dependencies in the right version.
I solved it by adding 2 annotations
#EnableAutoConfiguration
#EntityScan(basePackages = { "com.wt.rds" })
and my dependency was in gradle
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '2.0.4.RELEASE'
Unfortunately, most of the springboot guides on JPA integration test often lack a piece of configuration here and there.
So here is an example that hopefully should just work for you.
Point 1.
My local environment is currently setup to use springboot version:
<version.spring.boot>1.5.9.RELEASE</version.spring.boot>
That being said, I am currently setting up my local environment to be able to run integration tests against multiple databases (e.g. postgres, hsql, h2).
Therefore, I start by googling any random toturial that approaches this problem.
The next link is one such example:
https://www.baeldung.com/spring-testing-separate-data-source
The above example is a good starting point. It allows you to scoop up a valid Entity and a Valid repository. The springboot test class itself, on the other hand, leaves a lot ot be desired.
With the above example, you will immediately struggle with the integration test. You will get the usuable problems about the example not giving you the application.class to configure the integration test, and you are left hanging clueless as to what springboot annotations you need to put "where" to make the test to finally run without explosions.
So now I give you a MINIMAL set of 3 classes (Entity + Repository + SpringbootTest) that should hopefully have 100 percent of the configuration you need. This will serve as a basis of any JPA based integration test you will need to do in the future, then you can swap your entities and repositories, and continue testing with the same type of srpingboot configuration.
I start by giving you the IRRELEVANT classes. The stuff that is always the same, the stuff that you want to test, and that has nothing to do with configuration.
I am referring to REPOSITORY + ENTITY.
In eclipse create your java package:
tutorial.www.baeldung.com.tutorial001jpa.separateDS
Dump into this package the following trivial entity and repository classes, that are based on the tutorial reference I gave above.
Tutorial001GenericEntity
package tutorial.www.baeldung.com.tutorial001jpa.separateDS;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "TUTORIAL_001_GENERIC_ENTITY")
public class Tutorial001GenericEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String value;
public Tutorial001GenericEntity() {
super();
}
public Tutorial001GenericEntity(String value) {
super();
this.value = value;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
// standard constructors, getters, setters
}
Then we go for the second trivial code snippet.
The spring repository boiler plate code.
Tutorial001GenericEntityRepository
package tutorial.www.baeldung.com.tutorial001jpa.separateDS;
import org.springframework.data.jpa.repository.JpaRepository;
public interface Tutorial001GenericEntityRepository extends JpaRepository<Tutorial001GenericEntity, Long> {
}
At this point your maven project, src/test/java has a total of two classes. The basic stuff.
An entity and a repository, that serve as an example of any integration test you will ever need to do.
So now you go to the only important class in the example, the stuff that always gives a lot of problems, and that is the springboot test class which more then being responsible to test your business logic also has the complex task of CONFIGURING your test.
In this case, this test class has ALL IN ONE the annotations that allow springboot to disocver your entities, repositories, etc...
package tutorial.www.baeldung.com.tutorial001jpa.separateDS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
#RunWith(SpringRunner.class)
#ContextConfiguration(classes = {
tutorial.www.baeldung.com.tutorial001jpa.separateDS.Tutorial001GenericEntityIntegrationTest.ConfigureJpa.class })
#SpringBootTest()
public class Tutorial001GenericEntityIntegrationTest {
#EntityScan(basePackageClasses = { Tutorial001GenericEntity.class })
#EnableJpaRepositories(basePackageClasses = Tutorial001GenericEntity.class)
#EnableAutoConfiguration()
public static class ConfigureJpa {
}
#Autowired
private Tutorial001GenericEntityRepository genericEntityRepository;
#Test
public void givenTutorial001GenericEntityRepository_whenSaveAndRetreiveEntity_thenOK() {
Tutorial001GenericEntity genericEntity = genericEntityRepository.save(new Tutorial001GenericEntity("test"));
Tutorial001GenericEntity foundEntity = genericEntityRepository.findOne(genericEntity.getId());
assertNotNull(foundEntity);
assertEquals(genericEntity.getValue(), foundEntity.getValue());
}
}
The important thing, you see, is that this spring boot test has a class level annotation to provide to the springboot test the configuration context.
What we are doing is dumping one and only one class reference that represents our test configuration.
tutorial.www.baeldung.com.tutorial001jpa.separateDS.Tutorial001GenericEntityIntegrationTest.ConfigureJpa.class
And then on this little guy, you put all of the additional annotations in the world you need that springboot offers to configure applications.
In this case we have a dedicated annotation to mention entities.
Another to mention repositories.
And another to tell springboot to activate its auto configuration.
This springboot auto configuration annotation then does additional vodoo, like looking at your classpath and seeing that you have in the classpath say:
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>test</scope>
<version>2.3.4</version>
</dependency>
And it will immediately know how to configure an in memory data source for this database.
Behind the scenes, there might be additional configuration that is getting used.
For example, if you create an application.properties file in your src/test/resources that file will be considered.
It is very to see that the appliction.properties is considered by your running test.
If you want to verify this, make sure that in your test setup you do not have, for example, any dependency on the JDBC driver for postgres.
And then put into your application.properties something liek this:
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
This dialect is not compatible with HSQL or H2, so it will immediately make your green passing integration test blow up.
To be honest, I do not know if there is a simpler combo of annotations to properly configure the springboot scanning for an integration test.
As a rule, I would recommend that you try avoiding having hundreds of thousands of configuration classes in your src/test/resources.
Because if at some point you want to toggle all of your integration tests from using applicat-postgres.proeprties to application-hsql.properties, you might find yourself needing to tweak multiple configuration classes instead of just one.
So as rule, per maven component you write, I would try to have the tests that check repositories extend some sort of MyBaseINtegrationTestClass, and in there put this
#ContextConfiguration(classes = {
tutorial.www.baeldung.com.tutorial001jpa.separateDS.Tutorial001GenericEntityIntegrationTest.ConfigureJpa.class })
So that you only need to play with one configuration for testing for the hole project.
IN any case, hopefully the triplet of classes given here helps you.
One finel thing, for maven dependencies for integration testing, here is what I am using:
<!-- Test Dependencies JPA REPOSITORY TESTS -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
The reason why i am using hsql and h2 is beacuse I want my integration tests to be able to be tunned to either use application-hsql or application-h2.properties.

Java htmlunit: incompatible types for getPage?

In my code it is giving an error when trying to use the getPage method. I'm not sure what the problem is, any ideas of perhaps where I should be looking?
I've tried adding the class under "found" to my import but it doesn't seem to exist. This is my first time posting a java problem so please let me know if more information is needed.
The error:
java: incompatible types
required: com.gargoylesoftware.htmlunit.html.HtmlPage
found: com.gargoylesoftware.htmlunit.Page
My code
package com.buth.trabot;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.lang.Object;
import com.gargoylesoftware.htmlunit.*;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.WebClient;
import static org.junit.Assert.*;
/**
* Created with IntelliJ IDEA.
* User: Tyler
* Date: 9/28/13
* Time: 7:28 PM
* To change this template use File | Settings | File Templates.
*/
public class Main {
public static void main (String [] args) {
final WebClient webClient = new WebClient();
final HtmlPage startPage = webClient.getPage("http://htmlunit.sf.net");
assertEquals("HtmlUnit - Welcome to HtmlUnit", startPage.getTitleText());
}
}
My pom.xml file
<?xml version="1.0" encoding="UTF-8"?>
<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>MavenFirst</groupId>
<artifactId>MavenFirst</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>htmlunit</groupId>
<artifactId>htmlunit</artifactId>
<version>1.14</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
</dependencies>
</project>
It seems the return type of getPage is com.gargoylesoftware.htmlunit.Page.
Your variable is of type com.gargoylesoftware.htmlunit.html.HtmlPage.
You need to either change the type of your variable or add a cast.
I guess you should be linking it this way:
<dependency>
<groupId>net.sourceforge.htmlunit</groupId>
<artifactId>htmlunit</artifactId>
<version>2.12</version>
</dependency>

Categories