cucumber.runtime.CucumberException: Failed to instantiate class - maven

In my project I am trying to build framework using (Cucumber + TestNG + Maven).
Everything was working very well till I tried to run the tests on different browsers in parallel using the testng.xml file.
When I try to run the testng.xml, I receive the following error:
"cucumber.runtime.CucumberException: cucumber.runtime.CucumberException: Failed to instantiate class testSteps.TestLoginFun"
I think this is something wrong in my logic, or the connection between classes but I cannot find it.
This is the contents of my testng.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<!-- <suite name="Suite" parallel="false"> -->
<suite name="SuiteTestNG" parallel="tests">
<test name="Test on Firefox">
<parameter name="browser" value="Firefox" />
<classes>
<class name="runner.LoginTestRunner" />
</classes>
</test>
<test name="Test on Chrome">
<parameter name="browser" value="Chrome" />
<classes>
<class name="runner.LoginTestRunner" />
</classes>
</test>
</suite>
And this is my MavenCucumberProject.pom:
<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>MavenCucumberProject</groupId>
<artifactId>MavenCucumberProject</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<!-- <packaging>jar</packaging> -->
<!-- Change from here -->
<dependencies>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.0.0-beta3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-testng</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-core</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>com.github.mkolisnyk</groupId>
<artifactId>cucumber-reports</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>gherkin</artifactId>
<version>2.12.2</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.10.1</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-chrome-driver</artifactId>
<version>2.53.1</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-firefox-driver</artifactId>
<version>2.53.1</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-testng</artifactId>
<version>2.18.1</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<compilerVersion>1.8</compilerVersion>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
<repositories>
<repository>
<id>forplay-legacy</id>
<url>http://forplay.googlecode.com/svn/mavenrepo</url>
</repository>
</repositories>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
And this is my LoginTestRunner.java:
#RunWith(ExtendedCucumber.class)
#ExtendedCucumberOptions(jsonReport = "target/cucumber.json",
overviewReport = true,
outputFolder = "target")
#CucumberOptions(
features="Features",
tags = "#login",
glue="testSteps",
plugin={"html:target/cucumber-html-report",
"json:target/cucumber.json", "pretty:target/cucumber-pretty.txt",
"usage:target/cucumber-usage.json", "junit:target/cucumber-results.xml"})
public class LoginTestRunner extends AbstractTestNGCucumberTests{
public WebDriver driver;
#Parameters({"browser"})
#BeforeTest
public void chooseBrowser(String browser){
try {
if (browser.equalsIgnoreCase("Firefox")) {
driver = new FirefoxDriver();
System.out.println("Running Firefox");
} else if (browser.equalsIgnoreCase("Chrome")) {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
driver = new ChromeDriver();
System.out.println("Running Chrome");
}
}
catch (WebDriverException e) {
System.out.println(e.getMessage());
}
}
public WebDriver getDriver(){
driver.navigate().to("https://www.google.com");
driver.manage().window().maximize();
return driver;
}
public void closeDriver() {
driver.quit();
}
}
And my **TestLoginFun.java**:
public class TestLoginFun extends LoginTestRunner{
WebDriver driver;
CucumberResultsOverview results = new CucumberResultsOverview();
CucumberUsageReporting report = new CucumberUsageReporting();
#BeforeSuite
public void reports() throws Exception{
results.setOutputDirectory("target");
results.setOutputName("cucumber-results");
results.setSourceFile("./src/test/resources/cucumber.json");
report.setOutputDirectory("target");
report.setJsonUsageFile("target/cucumber.json");
report.executeReport();
}
public TestLoginFun(){
this.driver= getDriver();
}
#Given("^A user accessed the url https://www.google.com$")
public void a_user_accessed_the_url_https_www_google_com() throws Throwable {
driver.get("https://www.google.com");
}
Lastly my Features/Login.feature:
#login
Feature: Test Login
Scenario: Verify that all login fileds and objects are available
Given A user accessed the url https://www.google.com

So, recently I restructured my code according to this great post here:
https://rationaleemotions.wordpress.com/2013/07/31/parallel-webdriver-executions-using-testng/
This link guides you to build a Parallel WebDriver executions using TestNG.

Related

Maven skips tests specified in Cucumber runner, but if I run through testng they run successful

Using TestNG and Maven to run my Cucumber features. When running through Maven (mvn test) it just skips tests: Tests run: 1, Failures: 0, Errors: 0, Skipped: 1, Time elapsed: 2.071 sec - in TestSuite
But when running without Maven (simple running testngCucumber.xml file) it runs successfully.
Also when running TestRunner file it runs successfully.
Would appreciate any of why it could be happenning.
Pom.xml
<groupId>com.moodys.act</groupId>
<artifactId>ACT.TestAutomation</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>ACT.TestAutomation</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>testngCucumber.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-testng -->
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-testng</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>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-surefire-plugin -->
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
</dependency>
</dependencies>
testngCucumber.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test thread-count="5" name="Test">
<classes>
<class name="com.act.runner.TestRunner"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
TestRunner:
#CucumberOptions(features = "src/test/java/com/act/features", glue = "com/act/steps", tags = { "#ACT0001" })
public class TestRunner extends AbstractTestNGCucumberTests {
}

Unable to run cucumber test from command line - Success build response (No errors)

Nothing to compile - all classes are up to date - getting this
response from maven-compiler-plugin and no test cases are being
executed for Selenium - Cucumber Test Runner file
Changed the TestRunner name ending with test. Added the below
configuration in POM.xml file
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18</version>
<configuration>
<includes>
<excludes>**/*TestRunnertest.java</excludes>
</includes>
</configuration>
</plugin>
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>corporate</groupId>
<artifactId>web</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>web</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18</version>
<configuration>
<includes>
<excludes>**/*TestRunnertest.java</excludes>
</includes>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.aventstack</groupId>
<artifactId>extentreports</artifactId>
<version>3.0.7</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-chrome-driver</artifactId>
<version>3.141.59</version>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>4.2.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-junit</artifactId>
<version>2.3.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.5</version>
</dependency>
<dependency>
<groupId>org.apache.directory.studio</groupId>
<artifactId>org.apache.commons.io</artifactId>
<version>2.4</version>
</dependency>
</dependencies>
</project>
TestRunner
#RunWith(Cucumber.class)
#CucumberOptions(
features = "/Users/neha/eclipse-workspace/webCorp/src/test/java/feature", //the path of the feature files
glue={"stepDefinition"}, //the path of the step definition files
//format = { "pretty", "json:target/json/output.json" },
tags = { "~#ignore" },
plugin= {"com.cucumber.listener.ExtentCucumberFormatter:target/cucumber-reports/report.html"}, //to generate different types of reporting
monochrome = true, //display the console output in a proper readable format`enter code here`
strict = true, //it will check if any step is not defined in step definition file
dryRun = false //to check the mapping is proper between feature file and step def file
)
public class TestRunnertest {
#BeforeClass
public static void startup() {
System.out.println("Starting test");
}
}
I expect to be able to run the TestRunner file from commandline using
the cmd mvn test
-Dcucumber.options=”/Users/neha/eclipse-workspace/webCorp/src/main/java/testRunner/TestRunner.java”
I am able to run the code from eclipse by removing cucumber-java, junit and cucmber-junit dependency from pom.xml
Create TestNG.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="false">
<test name="Test">
<classes>
<class name="PackageName.TestRunnertest"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
Create pom.xml
Adding Dependencies and plugin TestNG.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>MavenOutlook</groupId>
<artifactId>MavenOutlook</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<selenium.version>3.12.0</selenium.version>
<testng.version>6.9.10</testng.version>
</properties>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.12.0</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.9.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.2.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-picocontainer</artifactId>
<version>1.2.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-testng</artifactId>
<version>1.2.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.vimalselvam</groupId>
<artifactId>cucumber-extentsreport</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>com.aventstack</groupId>
<artifactId>extentreports</artifactId>
<version>3.1.2</version>
</dependency>
<dependency>
<groupId>com.relevantcodes</groupId>
<artifactId>extentreports</artifactId>
<version>2.41.2</version>
</dependency>
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
<type>maven-plugin</type>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.3</version>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2-beta-5</version>
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.8</version>
</plugin>
<plugin>
<artifactId>maven-release-plugin</artifactId>
<version>2.3.2</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>TestNG.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>
</project>
Open a command prompt and go to the project directory
And run the test mvn test

How to test Spring CrudRepository using #DataJpaTest in Spring boot 2.1.0.M4 using Junit 5

I cannot test my spring crud repository using spring boot 2.1.0.M4 with Junit5 and #DataJpaTest.
I am using the following spring crud repository interface.
#Repository
public interface DestinationRepository extends CrudRepository<Destination, String> {
Optional<Destination> findCityCode(String code, String cityIsolci);
}
And this is my unit test class
package com.test.repository;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.test.Destination;
import java.util.Optional;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.junit4.SpringRunner;
#RunWith(SpringRunner.class)
#DataJpaTest
// #ExtendWith(SpringExtension.class)
public class DestinationRepositoryTest {
#Autowired
private TestEntityManager entityManager;
#Autowired
private DestinationRepository destinationRepository;
#Test
public void whenfindByCodeAndCityIsolciThenReturnDestination() throws Exception {
this.entityManager.persist(new Destination("DXB", "Y", "Dubai gate comment"));
Optional<Destination> found = destinationRepository.findByCodeAndCityIsolci("DXB", "Y");
Assert.assertTrue(found.isPresent());
// assertThat(user.getVin()).isEqualTo("1234");
}
// #Test
// public void whenfindByCodeAndCityIsolciThenReturnDestination() {
// // given
// Destination dubai = destinationRepository.save(new Destination("DXB", "Y", "Dubai gate comment"));
//
// // when
// Optional<Destination> found = destinationRepository.findByCodeAndCityIsolci("DXB", "Y");
//
// // then
// Assert.assertTrue(found.isPresent());
// Assert.assertEquals(found.get().getGateComment(), dubai.getGateComment());
// }
// #Test
// public void shouldFindAllDestinations() {
// Destination dubai = destinationRepository.save(new Destination("DXB", "Y", "Dubai gate comment"));
// Destination syd = destinationRepository.save(new Destination("SYD", "Y", "SYD gate comment"));
//
// Iterable<Destination> destinations = destinationRepository.findAll();
//
// assertThat(destinations).hasSize(2).contains(dubai, syd);
// }
}
This is my 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>
<parent>
<groupId>***.***.***</groupId>
<artifactId>******</artifactId>
<version>1.0.0</version>
<relativePath />
<!-- lookup parent from repository -->
</parent>
<artifactId>*****</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>${project.artifactId}</name>
<description>TEST</description>
<prerequisites>
<maven>${maven.version}</maven>
</prerequisites>
<properties>
<start-class>c*.*.Application</start-class>
<junit.jupiter.version>5.2.0</junit.jupiter.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-rsa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Sql server driver -->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
</dependency>
<!-- Lombok dependencies -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<!-- Commons dependencies -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
</dependency>
<!-- Logging dependencies -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<dependency>
<groupId>net.logstash.logback</groupId>
<artifactId>logstash-logback-encoder</artifactId>
</dependency>
<!-- Swagger dependencies -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-bean-validators</artifactId>
</dependency>
<!-- Test dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>com.vaadin.external.google</groupId>
<artifactId>android-json</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Spring REST Docs dependencies -->
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-webtestclient</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-asciidoctor</artifactId>
<scope>test</scope>
</dependency>
<!-- Spring Auto REST Docs dependencies -->
<dependency>
<groupId>capital.scalable</groupId>
<artifactId>spring-auto-restdocs-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>test</scope>
</dependency>
<!-- JUnit Jupiter API and Engine -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/mockwebserver -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>mockwebserver</artifactId>
<version>3.10.0</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.projectreactor/reactor-test -->
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<version>3.1.8.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mock-server</groupId>
<artifactId>mockserver-netty</artifactId>
<version>5.4.1</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<filtering>true</filtering>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
<include>**/*.yml</include>
</includes>
<excludes>
<exclude>**/*.jks</exclude>
</excludes>
</resource>
<resource>
<filtering>false</filtering>
<directory>src/main/resources</directory>
<includes>
<include>**/*.jks</include>
</includes>
<excludes>
<exclude>**/*.xml</exclude>
<exclude>**/*.properties</exclude>
<exclude>**/*.yml</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>com.github.ekryd.sortpom</groupId>
<artifactId>sortpom-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<configuration>
<excludeFromFailureFile>${project.basedir}/exclude-pmd.properties</excludeFromFailureFile>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
</plugin>
<plugin>
<groupId>org.gaul</groupId>
<artifactId>modernizer-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>pl.project13.maven</groupId>
<artifactId>git-commit-id-plugin</artifactId>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>dev</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<spring.profiles.active>dev</spring.profiles.active>
</properties>
</profile>
<profile>
<id>qa</id>
<properties>
<spring.profiles.active>qa</spring.profiles.active>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<spring.profiles.active>prod</spring.profiles.active>
</properties>
</profile>
<profile>
<id>eclipse</id>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<version>1.1.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
</dependency>
</dependencies>
</profile>
</profiles>
</project>
I just want to know what is the right set of annotations to run the test successfully.
I have tried using different combinations of
#DataJpaTest
#RunWith(SpringRunner.class)
#SpringBootTest(classes = Application.class)
#ExtendWith(SpringExtension.class)
If I just use #DataJpaTest with #RunWith(SpringRunner.class)
I get the following error:
[ERROR] whenfindByCodeAndCityIsolciThenReturnDestination Time elapsed: 1.237 s <<< ERROR!
org.springframework.dao.InvalidDataAccessResourceUsageException: could not prepare statement; SQL [insert into dbo.ek_destinations (city_isolci, gatecmt, code) values (?, ?, ?)]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement
at com.test.repository.DestinationRepositoryTest.whenfindByCodeAndCityIsolciThenReturnDestination(DestinationRepositoryTest.java:51)
Caused by: org.hibernate.exception.SQLGrammarException: could not prepare statement
at com.test.repository.DestinationRepositoryTest.whenfindByCodeAndCityIsolciThenReturnDestination(DestinationRepositoryTest.java:51)
Caused by: java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: EK_DESTINATIONS in statement [insert into dbo.ek_destinations (city_isolci, gatecmt, code) values (?, ?, ?)]
at com.test.repository.DestinationRepositoryTest.whenfindByCodeAndCityIsolciThenReturnDestination(DestinationRepositoryTest.java:51)
Caused by: org.hsqldb.HsqlException: user lacks privilege or object not found: EK_DESTINATIONS
at com.test.repository.DestinationRepositoryTest.whenfindByCodeAndCityIsolciThenReturnDestination(DestinationRepositoryTest.java:51)
P.S. Just want to mention that this was working fine with spring boot version 2.0.3.RELEASE.
I can see from the release notes (https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.1.0-M2-Release-Notes) that a bootstrap mode was introduced. This may or may not be causing the problem.
Do not mix #SpringBootTest with #DataJpaTest
From JavaDoc's one can read:
Annotation that can be used in combination with {#code
#RunWith(SpringRunner.class)} for a typical JPA test. Can be used
when a test focuses only on JPA components.
For full integration tests you should instead use #SpringBootTest
If you are looking to load your full application configuration, but use an embedded database, you should consider {#link SpringBootTest
#SpringBootTest} combined with {#link AutoConfigureTestDatabase
#AutoConfigureTestDatabase} rather than this annotation.
I think your problem is cause by changed naming strategy. Try to check this issue

#DataMongoTest is creating a null MongoTemplate

I have been trying to follow the instructions in the link below to try to add an automatically configured Embedded MongoDB Instance for Cucumber Integration testing. This is currently not working, since the I keep getting a null MongoTemplate. I thought that #DataMongoTest would automatically configure "#Autowired private MongoTemplate mongoTemplate;" Is this not the case? Below is my code:
mongoTemplate.save(doc, collection); throws a nullpointer exception.
#SpringBootTest(classes = AppCommentApiApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#DataMongoTest
public abstract class SpringIntegrationTest {
#Value("${local.server.port}")
public int port;
#Autowired
private MongoTemplate mongoTemplate;
protected void importJSON(String collection, String file) {
try {
for (String line : FileUtils.readLines(new File(file), "utf8")) {
Document doc = Document.parse(line);
mongoTemplate.save(doc, collection);
}
} catch (IOException e) {
throw new RuntimeException("Could not import file: " + file, e);
}
}
}
#RunWith(Cucumber.class)
#CucumberOptions(format = "pretty",
features = "src/test/resources/features",
glue = "com.app.comment.cucumber")
public class CucumberIntegrationTest {
}
public class StepDefinitions extends SpringIntegrationTest {
private Map<String, String> headerMap = null;
private String postBody = null;
private String putBody = null;
private String formData = null;
private Response response = null;
private String data = null;
private final static String MONGODB_COLLECTION = "comment";
private final static String MONGODB_DATA = "src/test/resources/mongodb-data/data.txt";
#Before
public void setup() {
importJSON(MONGODB_COLLECTION, MONGODB_DATA);
}
#Given("^the header information$")
public void the_header_information(Map<String, String> headerMap) throws Throwable {
this.headerMap = headerMap;
}
#Given("^post message body \"(.*?)\"$")
public void post_message_body(String postBody) throws Throwable {
this.postBody = postBody;
}
#Given("^put message body \"(.*?)\"$")
public void put_message_body(String putBody) throws Throwable {
this.putBody = putBody;
}
}
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.app.comment</groupId>
<artifactId>app-comment-api</artifactId>
<version>1.0.4</version>
<packaging>jar</packaging>
<name>app-comment-api</name>
<description>App Comments Microservice</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<log4j.version>2.4.1</log4j.version>
<commons.lang3.version>3.3.2</commons.lang3.version>
<guava.version>19.0</guava.version>
<swagger.version>2.4.0</swagger.version>
<surefire.junit47.version>2.18.1</surefire.junit47.version>
<rest-assured.version>2.8.0</rest-assured.version>
<jacoco.version>0.7.5.201505241946</jacoco.version>
<powermock.version>1.6.4</powermock.version>
<commons.io.version>2.4</commons.io.version>
<httpclient.version>4.5.1</httpclient.version>
<jayway.jsonpath.version>2.2.0</jayway.jsonpath.version>
<jjwt.version>0.6.0</jjwt.version>
<docker.image.prefix>app</docker.image.prefix>
<docker.spotify.plugin.version>0.4.5</docker.spotify.plugin.version>
<jacoco.maven.plugin.version>0.7.7.201606060606</jacoco.maven.plugin.version>
<fongo.version>2.0.11</fongo.version>
<cucumber.version>1.2.5</cucumber.version>
<gatling.highcharts.version>2.2.3</gatling.highcharts.version>
<gatling.plugin.version>2.2.1</gatling.plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator-docs</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-sleuth-zipkin</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.dropwizard.metrics</groupId>
<artifactId>metrics-core</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<!-- Utility -->
<dependency>
<groupId>com.logentries</groupId>
<artifactId>logentries-appender</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons.io.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons.lang3.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>${jayway.jsonpath.version}</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>${jjwt.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.6.5</version>
</dependency>
<!-- Test Dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.restassured</groupId>
<artifactId>rest-assured</artifactId>
<version>${rest-assured.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.jayway.restassured</groupId>
<artifactId>spring-mock-mvc</artifactId>
<version>${rest-assured.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-spring</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.gatling.highcharts</groupId>
<artifactId>gatling-charts-highcharts</artifactId>
<version>${gatling.highcharts.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Camden.SR5</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- Package as a docker image -->
<plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>${docker.spotify.plugin.version}</version>
<configuration>
<serverId>docker-hub</serverId>
<imageName>${docker.image.prefix}/${project.artifactId}</imageName>
<dockerDirectory>src/main/docker</dockerDirectory>
<resources>
<resource>
<targetPath>/</targetPath>
<directory>${project.build.directory}</directory>
<include>${project.build.finalName}.jar</include>
</resource>
</resources>
<imageTags>
<imageTag>${project.version}</imageTag>
</imageTags>
</configuration>
</plugin>
<!-- Runs Code Coverage Reports -->
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco.maven.plugin.version}</version>
<executions>
<execution>
<id>pre-unit-test</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>post-unit-test</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>cucumber-tests</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>none</exclude>
</excludes>
<includes>
<!-- Include your Cucumber tests, as an example -->
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*Simulation.scala</exclude>
</includes>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>gatling-tests</id>
<build>
<plugins>
<plugin>
<groupId>io.gatling</groupId>
<artifactId>gatling-maven-plugin</artifactId>
<version>${gatling.plugin.version}</version>
<executions>
<execution>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<simulationClass>com.app.comment.gatling.MicroserviceServiceSimulation</simulationClass>
</configuration>
</execution>
</executions>
<configuration>
<configFolder>${project.basedir}/src/test/resources</configFolder>
<dataFolder>${project.basedir}/src/test/resources/data</dataFolder>
<resultsFolder>${project.basedir}/target/gatling/results</resultsFolder>
<bodiesFolder>${project.basedir}/src/test/resources/bodies</bodiesFolder>
<simulationsFolder>${project.basedir}/src/test/scala</simulationsFolder>
<runDescription>This-is-the-run-description</runDescription>
<!-- <noReports>false</noReports> -->
<!-- <reportsOnly>directoryName</reportsOnly> -->
<!-- <simulationClass>foo.Bar</simulationClass> -->
<!-- <jvmArgs> -->
<!-- <jvmArg>-DmyExtraParam=foo</jvmArg> -->
<!-- </jvmArgs> -->
<!-- <fork>true</fork> -->
<!-- <propagateSystemProperties>true</propagateSystemProperties> -->
<!-- <failOnError>true</failOnError> -->
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-autoconfigured-mongo-test
If you use JUnit 4, you should have RunWith(SpringRunner.class). With JUnit 5 is not necessary.
And, #SpringBootTest cannot coexist with #DataMongoTest, because they are for different parts of the application and the latter is only for data part, while the former is for app part. (Actually the #BootstrapWith of them will conflict if you put these two together and the test cannot be start)
#DataMongoTest will use embedded database and you don't need to do extra config other than #Autowired the mongotemplate. If you want to use real db, do this:
#DataMongoTest(excludeAutoConfiguration = EmbeddedMongoAutoConfiguration.class)
My test is like this and it works:
#ActiveProfiles("db")
#DataMongoTest
class CouponTypeRefRepositoryTest {
#Autowired
private CouponTypeRefRepository repository; // a simple repository extending `DataMongoRepository`
#Autowired
private MongoTemplate mongoTemplate;
#BeforeEach
void prepare() {
CouponTypeRef toSave = CouponTypeRef.builder()
.id((short)1)
.duration((short)1)
.couponType("COMMERCIAL")
.couponTypeRefConfig(CouponTypeRefConfig.REFUNDABLE_NORMAL)
.build();
mongoTemplate.save(toSave, "CouponTypeRef");
}
#Test
void shouldReturnCouponTypeRef() {
Optional<CouponTypeRef> optional = repository.findById((short)1);
assertThat(optional.isPresent(), is(true));
assertThat(optional.get().getCouponType(), is("COMMERCIAL"));
assertThat(optional.get().getDuration(), is((short)1));
assertThat(optional.get().getCouponTypeRefConfig(), is(CouponTypeRefConfig.REFUNDABLE_NORMAL));
}
My dependency is:
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb-reactive:2.2.1.RELEASE'
The db profile config:
spring:
data:
mongodb:
host: localhost
port: 27017
database: app1
More info here:
https://www.baeldung.com/spring-boot-embedded-mongodb
https://docs.spring.io/spring-boot/docs/1.5.4.RELEASE/reference/html/boot-features-testing.html
Adding #RunWith(SpringRunner.class) annotation to SpringIntegrationTest class should work. SpringRunner will enable Autowiring of beans into your test class.
Try putting an #DirtiesContext on your test class.

JPA does not return any data from CloudSQL

I have project based on maven for deployment on GoogleAppEngine. I have local MySQL DB (for development) and remote CloudSQL DB (for production)
My code is based on google github
Data inside CloudSQL and MySQL are identical. I have a problem when trying to retrieve data via named query on production - list of size 0 is returned. On local MySQL DB code returns data correctly. I even tried to retrieve data from ClodSQL using standard java.sql.Connection and I was able to retrieve data. No data are returned only when requested from JPA.
Named query used:
#NamedQueries({(name = "Device.getDevices", = "SELECT d FROM Device d")
my persistence.xml
<?xml version="1.0" encoding="UTF-8" ?>
<persistence
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="transactions-optional-device">
<class>commander.apprecorder.database.pojos.device.Device</class>
<properties>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="datanucleus.autoCreateSchema" value="true"/>
</properties>
</persistence-unit>
</persistence>
Content of 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>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<groupId>group</groupId>
<artifactId>art</artifactId>
<properties>
<app.id>appid</app.id>
<app.version>version</app.version>
<appengine.version>1.9.30</appengine.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<gcloud.plugin.version>2.0.9.74.v20150814</gcloud.plugin.version>
<objectify.version>5.1.5</objectify.version>
<guava.version>18.0</guava.version>
<datanucleus.jpa.version>3.1.1</datanucleus.jpa.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.showDeprecation>true</maven.compiler.showDeprecation>
<cloudsql.device.url>
jdbc:google:mysql://some:instance:name/db?user=xxx
</cloudsql.device.url>
<cloudsql.device.url.dev>jdbc:mysql://localhost/db?user=x</cloudsql.device.url.dev>
<datanucleus-core.version>4.0.0-release</datanucleus-core.version>
<datanucleus-maven-plugin.version>4.0.0-release</datanucleus-maven-plugin.version>
<datanucleus-accessplatform-jpa-rdbms.version>4.0.0-release</datanucleus-accessplatform-jpa-rdbms.version>
<javax.persistence.version>2.1.0</javax.persistence.version>
</properties>
<prerequisites>
<maven>3.1.0</maven>
</prerequisites>
<dependencies>
<!-- Compile/runtime dependencies -->
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-api-1.0-sdk</artifactId>
<version>${appengine.version}</version>
</dependency>
<dependency>
<groupId>com.google.appengine.tools</groupId>
<artifactId>appengine-gcs-client</artifactId>
<version>0.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20151123</version>
</dependency>
<!--JPA start -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-accessplatform-jpa-rdbms</artifactId>
<version>${datanucleus-accessplatform-jpa-rdbms.version}</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>javax.persistence</artifactId>
<version>${javax.persistence.version}</version>
</dependency>
<!--JPA end -->
<!-- [START Objectify_Dependencies] -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>com.googlecode.objectify</groupId>
<artifactId>objectify</artifactId>
<version>${objectify.version}</version>
</dependency>
<!-- [END Objectify_Dependencies] -->
<!-- Test Dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>2.0.2-beta</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-testing</artifactId>
<version>${appengine.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-api-stubs</artifactId>
<version>${appengine.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<!-- for hot reload of the web application-->
<outputDirectory>${project.build.directory}/${project.build.finalName}/WEB-INF/classes</outputDirectory>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>versions-maven-plugin</artifactId>
<version>2.1</version>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>display-dependency-updates</goal>
<goal>display-plugin-updates</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<version>3.2</version>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
<dependencies>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-core</artifactId>
<version>${datanucleus-core.version}</version>
<scope>compile</scope>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<archiveClasses>true</archiveClasses>
<webResources>
<!-- in order to interpolate version from pom into appengine-web.xml -->
<resource>
<directory>${basedir}/src/main/webapp/WEB-INF</directory>
<filtering>true</filtering>
<targetPath>WEB-INF</targetPath>
</resource>
</webResources>
</configuration>
</plugin>
<plugin>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-maven-plugin</artifactId>
<version>${appengine.version}</version>
<configuration>
<enableJarClasses>false</enableJarClasses>
<version>${app.version}</version>
<!-- Comment in the below snippet to bind to all IPs instead of just localhost -->
<!-- address>0.0.0.0</address>
<port>8080</port -->
<!-- Comment in the below snippet to enable local debugging with a remote debugger
like those included with Eclipse or IntelliJ -->
<!-- jvmFlags>
<jvmFlag>-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n</jvmFlag>
</jvmFlags -->
</configuration>
</plugin>
<plugin>
<groupId>com.google.appengine</groupId>
<artifactId>gcloud-maven-plugin</artifactId>
<version>${gcloud.plugin.version}</version>
<configuration>
<set_default>true</set_default>
</configuration>
</plugin>
<!--DB start-->
<plugin>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-maven-plugin</artifactId>
<version>${datanucleus-maven-plugin.version}</version>
<configuration>
<api>JPA</api>
<persistenceUnitName>transactions-optional-device</persistenceUnitName>
<fork>false</fork>
<!--<persistenceUnitName>Demo</persistenceUnitName>-->
<!--<log4jConfiguration>${basedir}/log4j.properties</log4jConfiguration>-->
<verbose>true</verbose>
</configuration>
<executions>
<execution>
<phase>process-classes</phase>
<goals>
<goal>enhance</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-core</artifactId>
<version>${datanucleus-core.version}</version>
</dependency>
</dependencies>
</plugin>
<!--JPA end-->
</plugins>
</build>
And servlet for JPA
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/plain");
Map<String, String> properties = new HashMap();
if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) {
properties.put("javax.persistence.jdbc.driver", "com.mysql.jdbc.GoogleDriver");
properties.put("javax.persistence.jdbc.url", System.getProperty("cloudsql.device.url"));
} else {
properties.put("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver");
properties.put("javax.persistence.jdbc.url", System.getProperty("cloudsql.device.url.dev"));
}
// List all the rows.
EntityManagerFactory emf = Persistence.createEntityManagerFactory(
"transactions-optional-device", properties);
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
resp.getWriter().println("performing query");
List<Device> result = em.createNamedQuery("Device.getDevices", Device.class).getResultList();
resp.getWriter().println("Starting to list devices - " + result.size());
for (Device g : result) {
resp.getWriter().println(g.getA() + "_" + g.getB());
}
em.getTransaction().commit();
em.close();
}
There is no error inside app engine log. Can you please tell me what is wrong? Thanks :)
I set log level to ALL and found out that Datanucleus was trying to access datastore. It created new table inside datastore and retrieved its content - no data.
I have no idea why it was trying to access datastore and was not using CloudSQL, but nevermind...
I replaced DataNucles for Hibernate by tutorial inside google github and it worked on first time
Migration was easy, only persistance.xml and pom.xml had to be modified.

Resources