I am starting to use spring boot framework and stumble on every second step.
Currently I have a situation which i absolutely do not understand.
I am using spring boot 2.3.5.RELEASE building with maven
<properties>
<java.version>11</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.5.RELEASE</version>
<relativePath/>
<!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.1.6.Final</version>
</dependency>
<!-- OpenAPi (swagger)-->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.2.32</version>
</dependency>
</dependencies>
I created a rather simple class RESTCommunication. No #Component, #Controller or similar.
public class RESTCommunication {
private final Logger m_logger = LoggerFactory.getLogger(this.getClass());
private String m_contentType;
private String m_path;
private String m_body;
private HashMap<String,String> m_urlParams;
private HashMap<String,String> m_queryParams;
public RESTCommunication() {
m_logger.debug("RESTCommunication constructor");
m_scheme = RESTCommunication.SCHEME_DEFAULT;
m_authority = RESTCommunication.AUTHORITY_DEFAULT;
m_port = RESTCommunication.PORT_DEFAULT;
m_path = RESTCommunication.PATH_DEFAULT;
m_urlParams = new HashMap<>();
// m_queryParams = new HashMap<>(); // I know that this is the reason for the exception
}
#Override
public String toString() {
StringBuilder sbToString = new StringBuilder();
sbToString.append(buildURI());
sbToString.append("|numURLParams:").append(m_urlParams.size());
sbToString.append("|numQueryParams:").append(m_queryParams.size()); // This has to fail because m_queryParams is not initialized
return sbToString.toString();
}
.....
For this class i created a very simple test class RESTCommunicationTest
#SpringBootTest
public class RESTCommunicationTest {
private final Logger m_logger = LoggerFactory.getLogger(this.getClass());
#Test
public void defaultInitTest() {
RESTCommunication restComm = new RESTCommunication();
String restCommURL = restComm.toString(); // Expect the nullpointer INSIDE the toString method
String expectedURL = sbExpected.toString();
assertEquals(expectedURL, restCommURL, "Expected URL does not match generated");
}
I run the test with the command: $./mvnw -e -X package -Dtest=RESTCommunicationTest#defaultInitTest
And as expectable i see the Nullpointer in the stdout logging.
BUT in the logging I find this:
webServerFactoryCustomizerBeanPostProcessor
websocketServletWebServerCustomizer
welcomePageHandlerMapping
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 3.532 s <<< FAILURE! - in org.highpots.hippo.core.communication.RESTCommunicationTest
[ERROR] defaultInitTest Time elapsed: 0.399 s <<< ERROR!
java.lang.NullPointerException
at org.ilovespringboot.not.RESTCommunicationTest.defaultInitTest(RESTCommunicationTest.java:36)
2020-12-08 22:18:10.810 INFO 10381 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
[INFO]
[INFO] Results:
[INFO]
[ERROR] Errors:
[ERROR] RESTCommunicationTest.defaultInitTest:36 » NullPointer
[INFO]
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
A nullpointer in RESTCommunicationTest.java:36. Absolutely no hint that the real NullPointer happens in RESTCommunication class.
Can someone explain my that behaviour? Am I doing something wrong?
I know I am some kind of programming dinosaurs. (java projects are about 10+ years in the past). But I would expect to get a hint where the exception is thrown. I would expect a stacktrace with detailed caused by sections.
If can not imagine this is not normal behavior. Because that would mean I have to find all errors by mind-stepping through the complete source... This is not possible
Tanks for your help in advance
Harri E
Maven uses surefire plugin to run tests.To see Exception stacktrace you must set trimStackTrace to false in surefire plugin configuration.
Historically surefire plugin use to print complete stacktrace. Though the information in the stack trace was useful for debugging, stack traces took up rather a lot of space in the console output. Particularly if there were a number of failing tests it became easy to get lost in the noise.
Since version 2.13 surefire just prints summary by default.
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${your.maven.surefire.version.here}</version>
<configuration>
<trimStackTrace>false</trimStackTrace>
</configuration>
</plugin>
</plugins>
</build>
Related
I use Maven on my test project and I wanted to test test option in Maven's lifecycle, but my JUnit test failed. I have a class named Arithmetics in src.main.java package and a class named ArithmeticsTest in src.test.java package.
When I run ArithmeticsTest on my own using IntelliJ IDEA everything works OK, and I have expected java.lang.AssertionError, so why I don't have such when I run test option in maven?
Console output:
T E S T S
Results :
Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
src.main.java.Arithmetics.java
public class Arithmetics
{
public static int add(int a, int b)
{
return a + b;
}
}
src.test.java.ArithmeticsTest.java
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class ArithmeticsTest
{
#Test
public void testAdd()
{
assertEquals(4, Arithmetics.add(2, 3));
}
}
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>groupId</groupId>
<artifactId>Test</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>15</maven.compiler.source>
<maven.compiler.target>15</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
There are three wrong things I can spot based on your question, while they might not provide a complete answer I hope they'll will be a step in a right direction:
src/main/java and src/test/java is not a package as you write. Its a folder layout supported by maven, basically , if you have a code in com.myorg.somepackage.Arithmetics
Make sure you have the following layout at the level of actual physical folders:
src
main
java
com
myorg
somepackage
Arithmetics.java
test
java
com
myorg
somepackage
ArithmeticsTest.java
For both java files the package must be com.myorg.somepackage:
package com.myorg.somepackage;
public class Arithmetics {}
And
package com.myorg.somepackage;
public class ArithmeticsTest {}
I know it might be a wrong naming that you've used in the question, but still I have to state it because it might cause an actual issue
The second issue is that for some reason you seem to configure your surefire plugin to use test ng which is an alternative to junit. It can happen because testng is placed as a dependency - I can only speculate because you don't really show the full surefire plugin configure and do not provide a full list of dependencies, but you've got and idea I believe :)
This is wrong because you use the junit5 dependencies as well as the imports that correspond to the junit 5.
The dependencies on the junit 5 are completely messy:
You seem to have two dependencies on just the same with the different scope, its really a wrong thing to do. Make sure you use only the test scope and have all the relevant dependencies. Read here for instruction of how to configure the surefire plugin
In addition, for the sake of completeness of the answer, check that you use the recent version of surefire plugin, if its too old the chances are that it won't be able to run jupiter engine (junit 5)
As other answer already pointed out few things which may go wrong in your case, I am just adding the solution to your pom xml.
The surefire plugin version is the main culprit. Default with maven (2.12.4) will not work with junit-5 jupiter engine.
So just add the plugin in your with version 2.22.1 in your pom, it should work after that, assuming your folder structure as per required (see other answer).
<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
</plugins>
</pluginManagement>
</build>
I am unable to control the treads from dataproviderthreadcount.
For example if we have 4 scenario and I run my script, it execute all 4 scenario's parallelly. Doesn't matter what dataproviderthreadcount value I gave in the pom for maven-surfire.
Below are the snapshots.
POM:
<?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>testParallerRun</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<cucumbertestng.version>5.6.0</cucumbertestng.version>
<cucumberjava.version>5.6.0</cucumberjava.version>
<mvncompiler.version>3.8.1</mvncompiler.version>
<javarelease.version>11</javarelease.version>
<mvnsurefire.version>3.0.0-M5</mvnsurefire.version>
</properties>
<dependencies>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-testng</artifactId>
<version>${cucumbertestng.version}</version>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>${cucumberjava.version}</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${mvncompiler.version}</version>
<configuration>
<release>${javarelease.version}</release>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${mvnsurefire.version}</version>
<configuration>
<properties>
<property>
<name>dataproviderthreadcount</name>
<value>2</value>
</property>
</properties>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
Runner Class:
package com.test.runner;
import io.cucumber.testng.AbstractTestNGCucumberTests;
import io.cucumber.testng.CucumberOptions;
import org.testng.annotations.DataProvider;
#CucumberOptions(
plugin = {
"pretty",
"json:target/reports/json/result.json",
"html:target/reports/html/result.html"},
strict = true,
features = {"src/test/resources/"},
glue = {"com.test.stepdef"},
tags = {""}
)
public class TestRunner extends AbstractTestNGCucumberTests {
#DataProvider(parallel = true)
#Override
public Object[][] scenarios() {
return super.scenarios();
}
}
Feature 1:
Feature: test 1
Scenario: 01
Given Print "01"
Scenario: 02
Given Print "02"
Scenario: 03
Given Print "03"
Scenario: 04
Given Print "04"
Please let me if anyone know how to control the number of threads rather than let Testng decide.
There's no problem with TestNG per se here.
The dataproviderthreadcount attribute that you have set in your pom file is going to be applicable and relevant only when you are running your test via mvn clean test.
If you are trying to run this test class from within the IDE (IntelliJ or Eclipse for that matter) its not going take affect.
Here's a test class that I created which is powered by a data provider ( For the sake of simplicity I have intentionally kept cucumber out of the equation )
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class AppTest {
#Test(dataProvider = "dp")
public void shouldAnswerWithTrue(int i) {
System.err.println("Running on [" + Thread.currentThread().getId() + "]");
}
#DataProvider(name = "dp", parallel = true)
public Object[][] testData() {
return new Object[][]{
{1},
{2},
{3},
{4},
{5},
{6}
};
}
}
Here's the command line output when I run mvn clean test
[INFO] --- maven-surefire-plugin:3.0.0-M5:test (default-test) # testng_playground ---
[INFO]
[INFO] -------------------------------------------------------
[INFO] T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.rationaleemotions.AppTest
Running on [15]
Running on [14]
Running on [15]
Running on [14]
Running on [14]
Running on [15]
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.62 s - in com.rationaleemotions.AppTest
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
I encountered the exact same. As Krishnan mentioned, the dataproviderthreadcount in pom.xml works only when you run mvn test but without any parameter. If you want to specify which suite xml to run, you will need to add -Ddataproviderthreadcount=2 in command line as well. For example, "mvn -Dsurefire.suiteXmlFiles=suite.xml -Ddataproviderthreadcount=2 test"
I am new to coding. I am getting below error when trying to run java application in springboot with H2db.
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 8.777 s <<< FAILURE! - in com.example.demo.DemoApplicationTests
[ERROR] contextLoads(com.example.demo.DemoApplicationTests) Time elapsed: 0.002 s <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
[INFO]
[INFO] Results:
[INFO]
[ERROR] Errors:
[ERROR] DemoApplicationTests.contextLoads » IllegalState Failed to load ApplicationCon...
[INFO]
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 13.028 s
[INFO] Finished at: 2019-05-26T22:46:54+05:30
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.22.2:test (default-test) on project demo: There are test failures.
[ERROR]
[ERROR] Please refer to C:\Users\v\Desktop\demo\target\surefire-reports for the individual test results.
[ERROR] Please refer to dump files (if any exist) [date].dump, [date]-jvmRun[N].dump and [date].dumpstream.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
Here is my 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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Application :
package com.example.demo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import com.example.demo.StudentRepository;
#SpringBootApplication
#EntityScan("com.example.demo.Student")
#EnableJpaRepositories("com.example.demo.StudentRepository")
public class H2demoApplication implements CommandLineRunner {
// mvn spring-boot:run
private Logger LOG = LoggerFactory.getLogger("H2demoApplication");
StudentRepository studentRepository;
#Autowired
public H2demoApplication(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
public static void main(String[] args) {
SpringApplication.run(H2demoApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
LOG.info("Student count in DB: {}", studentRepository.count());
}
}
Entity:
package com.example.demo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Student {
#Id
#GeneratedValue
private Long ID;
private String NAME;
private String SECTION;
public Student() {
}
public Student(Long ID, String NAME, String SECTION) {
this.ID = ID;
this.NAME = NAME;
this.SECTION = SECTION;
}
public Long getId() {
return ID;
}
public void setId(Long ID) {
this.ID = ID;
}
public String getName() {
return NAME;
}
public void setName(String NAME) {
this.NAME = NAME;
}
public String getSection() {
return SECTION;
}
public void setSection(String SECTION) {
this.SECTION = SECTION;
}
}
Repository:
package com.example.demo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.demo.Student;
#Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
}
O/p should have "Student count in DB: 2"
my java version is :
java version "1.8.0_102"
Java(TM) SE Runtime Environment (build 1.8.0_102-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode)
Getting above error when running mvn clean install in command line.
I defined h2db configurations in application.properties file as below
H2 configurarion
spring.h2.console.enabled=true
spring.h2.console.path=/h2
Datasource
spring.datasource.url=jdbc:h2:~/test
spring.datasource.username=
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
in data.sql file kept data to be inserted :
insert into STUDENT
values(10001,'Ajay', 'AAA1');
insert into STUDENT
values(10002,'Ajit', 'AAA2');
You need to provide the hibernate dialect to configure hibernate befor connecting
use
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
The error looks like, it can't figure out the dialect to be used with H2.
The dialect specifies the type of database used in hibernate so that hibernate generate appropriate type of SQL statements.
The dialect to be used for h2 is this:
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
Also being new to programming might confuse you to write optimal code. It looks like, you are mixing up things from older versions of spring boot and spring. Please use,
https://start.spring.io
to generate your initial spring boot project with the required dependencies. You can follow the below tutorial which explains nicely to get started with spring boot and h2.
https://www.springboottutorial.com/spring-boot-and-h2-in-memory-database
I have a Cucumber-Selenium based test written using Spring Boot. The problem is that if I have just one step definition file GoolgeCalcStepDefinition.java then the program works and test passes without any issue but as soon as I added BingSearchStepDefinition.java along with feature file then I get following error.
I googled around on how to configure Spring Boot with Cucumber but most of the examples/articles available online shows only one step definition file.
mvn verify
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.example.TestRunner
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.368 sec <<< FAILURE! - in com.example.TestRunner
initializationError(com.example.TestRunner) Time elapsed: 0.004 sec <<< ERROR!
cucumber.runtime.CucumberException: Glue class class com.example.stepdefs.GoogleCalcStepDefinition and class com.example.stepdefs.BingSearchStepDefinition both attempt to configure the spring context. Please ensure only one glue class configures the spring context
Results :
Tests in error:
TestRunner.initializationError » Cucumber Glue class class com.example.stepdef...
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
[ERROR] There are test failures.
Please refer to I:\pet-projects\junit-cucumber-demo\target\surefire-reports for the individual test results.
[INFO]
[INFO] --- maven-jar-plugin:3.0.2:jar (default-jar) # junit-cucumber-demo ---
[INFO] Building jar: I:\pet-projects\junit-cucumber-demo\target\junit-cucumber-demo-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:2.0.6.RELEASE:repackage (default) # junit-cucumber-demo ---
[INFO]
[INFO] --- maven-cucumber-reporting:3.14.0:generate (execution) # junit-cucumber-demo ---
ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console. Set system property 'org.apache.logging.log4j.simplelog.StatusLogger.level' to TRACE to show Log4j2 internal initialization logging.
[INFO] About to generate Cucumber report.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 9.718 s
[INFO] Finished at: 2019-04-14T16:04:55-04:00
[INFO] ------------------------------------------------------------------------
TestRunner.java
#RunWith(Cucumber.class)
#CucumberOptions(
plugin = {"pretty", "json:target/cucumber-reports/cucumber.json"},
glue = {"com.example.stepdefs"},
features = {"src/test/resources/features"})
public class TestRunner {
}
DemoApplicationTests.java
#RunWith(SpringRunner.class)
#SpringBootTest
public abstract class DemoApplicationTests {
}
GoogleCalcStepDefinition.java
#Ignore
public class GoogleCalcStepDefinition extends DemoApplicationTests {
WebDriver driver;
GoogleSearchPage googleSearchPage;
#Given("^I open Google$")
public void I_open_google() {
this.driver = BrowserConfig.getWebDriver();
this.googleSearchPage = PageFactory.initElements(driver, GoogleSearchPage.class);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://www.google.com");
}
#When("^I enter \"([^\"]*)\" in search textbox$")
public void I_enter_in_search_textbox(String input) {
googleSearchPage.searchBox.sendKeys(input); //passing 2+2 and 5*5 here
googleSearchPage.searchBtn.click();
}
#Then("^I should get result as \"([^\"]*)\"$")
public void I_should_get_correct_result(String expectedResult) {
String result = googleSearchPage.calculatorTextBox.getText();
assertEquals(result, expectedResult); //Verify that result of 2+2 is 4 and 5*5 is 25
BrowserConfig.releaseResources(driver);
}
}
BingSearchStepDefinition.java
#Ignore
public class BingSearchStepDefinition extends DemoApplicationTests {
WebDriver driver;
BingSearchPage bingSearchPage;
#Given("^I open Bing$")
public void I_open_bing() {
this.driver = BrowserConfig.getWebDriver();
this.bingSearchPage = PageFactory.initElements(driver, BingSearchPage.class);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://www.bing.com");
}
#When("^I enter \"([^\"]*)\" in search textbox$")
public void I_enter_in_search_textbox(String input) {
bingSearchPage.searchBox.sendKeys(input); //passing searchTerm = Ostrich
bingSearchPage.searchBtn.click();
}
#Then("^I should get result as \"([^\"]*)\"$")
public void I_should_get_correct_result(String input) {
String result = driver.getTitle();
System.out.println("result: " + result);
assertEquals(result, input); //Verify that result = Bing - <searchTerm>
BrowserConfig.releaseResources(driver);
}
}
google.feature
Feature: Check addition in Google calculatorcontent
In order to verify that Google calculator work correctly
As a user of Google
I should be able to get correct addition result
Background: Do some arithmetic on Google
Given I open Google
Scenario: Addition
When I enter "2+2" in search textbox
Then I should get result as "4"
Scenario: Multiplication
When I enter "5*5" in search textbox
Then I should get result as "25"
bing.feature
Feature: Check search in Bing
In order to verify that Bing search works correctly
As a user of Bing
I should be able to get correct search result
Scenario: Bird
Given I open Bing
When I enter "Ostrich" in search textbox
Then I should get page title result as Bing " - Ostrich"
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>4.2.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-junit</artifactId>
<version>4.2.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-spring</artifactId>
<version>4.2.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-chrome-driver</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-chrome-driver</artifactId>
<version>2.45.0</version>
<scope>test</scope>
</dependency>
Both of your runner classes extend DemoApplicationTests.java which is itself a #SpringBootTest.
Cucumber cannot determine which SpringBootContext to load when it fires up.. remove the class extends from your stepdefs and have TestRunner extend DemoApplicationTests instead
I need to be able to use the profile activated during the run time of JUnit tests.
I was wondering if there is any way of doing something like:
String str = System.getProperty("activated.profile[0]");
Or any other relative way...
I realized there is an option to use ${project.profiles[0].id} bu somehow it's not working.
Any ideas?
When using surefire to run the unit tests, it usually spawns a new JVM to run the tests, and we have to pass the information to the new JVM. This can be done usually using the "systemPropertyVariables" tag.
I was able to exercise this using a quickstart Java project, where I added this to the POM:
I declared the following profiles
<profiles>
<profile>
<id>special-profile1</id>
</profile>
<profile>
<id>special-profile2</id>
</profile>
</profiles>
And this to surefire configuration:
<build>
<plugins>
...
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19</version>
<configuration>
<systemPropertyVariables>
<profileId>${project.activeProfiles[0].id}</profileId>
</systemPropertyVariables>
</configuration>
</plugin>
...
</plugins>
</build>
And in my unit test, I added this:
/**
* Rigourous Test :-)
*/
public void testApp()
{
System.out.println("Profile ID: " + System.getProperty("profileId"));
}
When invoking the "test" command without profile (i.e. using mvn test), I got this:
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.fxs.AppTest
Profile ID: development
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.003 sec - in com.fxs.AppTest
Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
And we I used mvn -P special-profile2 test, I got this
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.fxs.AppTest
Profile ID: special-profile2
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 sec - in com.fxs.AppTest
Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
This will pass along the name of the first active profile. If we have potentially more than one active profiles, then we will probably need to use more system properties.
Note: I tested this using Maven 3.1.1
I other cases I used next in pom file:
<profiles>
<profile>
<id>a-profile-id</id>
<properties>
<flag>a-flag-value</flag>
</properties>
</profile>
</profiles>
and in java:
String flagValue = System.getenv("flag");