Why is my IE browser getting launched twice with Selenium and Cucumber? - java

I am writing very basic automation test with Selenium-Cucumber that is launching an IE browser and closing it at the end.
The problem is that the browser gets launched twice.
The test does not have much it other than few System.out statements. I am kind of new to both selenium-based automation testing and Cucumber and not able to understand why is it getting launched twice.
Please guide.
BrowserConfig.java
public class BrowserConfig {
private static final String IE_DRIVER_EXE = "drivers/IEDriverServer.exe";
private static final String WEBDRIVER_IE_DRIVER = "webdriver.ie.driver";
private static final String BASE_URL = "https://www.google.com";
public static WebDriver getIEWebDriver() {
String filePath = ClassLoader.getSystemClassLoader().getResource(IE_DRIVER_EXE).getFile();
System.setProperty(WEBDRIVER_IE_DRIVER, filePath);
InternetExplorerOptions options = new InternetExplorerOptions().requireWindowFocus();
options.setCapability(INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
options.setCapability(ENABLE_ELEMENT_CACHE_CLEANUP, true);
options.setCapability(IE_ENSURE_CLEAN_SESSION, true);
options.setCapability(ACCEPT_SSL_CERTS, true);
options.setCapability("nativeEvents", false);
options.setCapability(INITIAL_BROWSER_URL, BASE_URL);
WebDriver driver = new InternetExplorerDriver(options);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
return driver;
}
public static void releaseResources(WebDriver driver) {
if (null != driver) {
driver.close();
driver.quit();
}
}
}
TestRunner.java
#RunWith(Cucumber.class)
#CucumberOptions(
plugin = {"pretty", "json:target/cucumber-reports/cucumber.json"},
features = {"src/test/resources/features"})
public class TestRunner extends ApplicationTests {
}
LoginStep.java
#Ignore
public class LoginStep {
WebDriver driver;
#Before
public void setup() {
if (this.driver == null) {
this.driver = BrowserConfig.getIEWebDriver();
}
}
#After
public void cleanUp() {
BrowserConfig.releaseResources(driver);
}
#Given("^The user is on the Login page$")
public void doLogin() {
System.out.println("The user is on the Login page");
}
#When("^The user enters the correct credentials on the Login page$")
public void setWelcomePage() {
System.out.println("The user enter the correct credentials on the Login page");
}
#Then("^The user is displayed Welcome page$")
public void validate() {
System.out.println("The user is displayed Welcome page");
}
}
HelpStep.java
#Ignore
public class HelpStep {
WebDriver driver;
#Before
public void setup() {
if (this.driver == null) {
this.driver = BrowserConfig.getIEWebDriver();
}
}
#After
public void cleanUp() {
BrowserConfig.releaseResources(driver);
}
#When("^The user clicks on the Help menu link from the Welcome page$")
public void setWelcomePage() {
System.out.println("The user clicks on the Help menu link from the Welcome page");
}
#Then("^The user is displayed Help page$")
public void validate() {
System.out.println("The user is displayed Help page");
}
}
help.feature
Feature: Check that the user is able to navigate to Help page
Background:
Given The user is on the Login page
When The user enters the correct credentials on the Login page
Then The user is displayed Welcome page
Scenario:
When The user clicks on the Help menu link from the Welcome page
Then The user is displayed Help page
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>cucumber-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>cucumber-demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<cucumber.version>4.2.3</cucumber.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-junit</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-spring</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<configuration>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
<plugin>
<groupId>net.masterthought</groupId>
<artifactId>maven-cucumber-reporting</artifactId>
<version>3.14.0</version>
<executions>
<execution>
<id>execution</id>
<phase>verify</phase>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<projectName>${project.artifactId}</projectName>
<outputDirectory>${project.build.directory}/cucumber-reports</outputDirectory>
<cucumberOutput>${project.build.directory}/cucumber-reports/cucumber.json</cucumberOutput>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>

Because you are initializing and call your driver twice in feature files.
Background part of your feature file are initializing browser firstly in LoginStep.java then your Scenario is also initialize browser in HelpStep.java.
I prefer using global Hooks.java class for #Before and #After hooks and inject driver between different .java classes.

Found the solution. The below sample code is not the same as original post but this fixes the issue. Added new class "Hooks.java" that contains common steps and removed "Background" from feature files. That helped fix the issue.
Hooks.java
public class Hooks {
public static WebDriver driver;
#Before
public void setUp() {
System.out.println("Into the setup method of AccountStep...");
driver = BrowserConfig.getDriver();
}
#After
public void cleanUp() {
System.out.println("Into the cleanUp method of AccountStep...");
if (null != driver) {
driver.close();
driver.quit();
}
}
}
help.feature
Feature: Check that the user is able to navigate to Help page
Scenario:
Given The user is on the Help page
When The user clicks on the links within the Help page
Then The user is navigated to that Help section
HelpStep.java
#Ignore
public class HelpStep {
private WebDriver driver;
public HelpStep() {
this.driver = Hooks.driver;
}
#Given("^The user is on the Help page$")
public void onPage() {
System.out.println("The user is on the Help page");
}
#When("^The user clicks on the links within the Help page$")
public void clickLinks() {
System.out.println("The user clicks on the links within the Help page");
}
#Then("^The user is navigated to that Help section$")
public void validate() {
System.out.println("The user is navigated to that Help section");
}
}

Make sure you specific the before and after hooks with tag for every Feature, Why ? ok for example you have two features called UsersFeature and ProductsFeature and you make some hooks like initBrowser as before and closeBrowser as after for UsersFeature and ProductsFeature what happens when you run that test without any tags ? let me tell you that hooks it will running for tow times or (N times for parallel) for every Feature for that test and N = "number of the features in that test" so all the before hooks in that test will runing first even if there is million Features and also the all the after hooks so make sure use tags like #Before('#users_feature') #After('#users_feature') in that time that hooks will runing only when the test executing the feature scenarios with #users_feature tag

Related

Version update to SELNEIUM 4.7.0 throwing NoSuchMethod Exception for Pagefactory

I'm changing my selenium porject from 3.141 to 4.7.0 but i'm seeing NoSuchElementException on PageFactory Initialization.
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.7.1</version>
</dependency>
public WebElementsLogin(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(this.driver, this);
}
java.lang.NoSuchMethodError: 'void org.openqa.selenium.support.PageFactory.initElements(org.openqa.selenium.SearchContext, java.lang.Object)'
Using selenium 4.7.1 and JDK 11:
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.7.1</version>
</dependency>
public class Google {
private WebDriver driver;
#FindBy(name = "q")
private WebElement searchField;
public Google(WebDriver driver){
this.driver = driver;
PageFactory.initElements(driver, this);
}
public void searchFor(String text){
searchField.sendKeys(text);
searchField.sendKeys(Keys.ENTER);
}
public void navigateTo(){
driver.get("https://google.com");
}
public static void main(String[] args) {
WebDriverManager.chromedriver().setup();
WebDriver chrome = new ChromeDriver();
Google google = new Google(chrome);
google.navigateTo();
google.searchFor("Selenium");
}
}
Everything works as expected.
Correct this line:
PageFactory.initElements(this.driver, this);

Problem with unit tests: Junit and the Mockito framework

I am learning to do unit and double tests with Junit and the Mockito framework, but I am not getting the expected result in a specific test with 'mocks'. I do an assertThat that should return positive test, instead, it returns an error that says Mockito cannot mock this class. It is a class called 'Console' that must print and collect values ​​from the user's keyboard, but of course, in unit tests this should be 'mocked' to avoid 'intervening test' in antipattern, where the test asks for data to the developer, that is, I need to 'mock up' a user input. This 'Console' class is like a small facade of the typical java BufferedReader class.
I pass you the classes involved:
Console:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Console {
private BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
public String readString(String title) {
String input = null;
boolean ok = false;
do {
this.write(title);
try {
input = this.bufferedReader.readLine();
ok = true;
} catch (Exception ex) {
this.writeError("characte string");
}
} while (!ok);
return input;
}
public int readInt(String title) {
int input = 0;
boolean ok = false;
do {
try {
input = Integer.parseInt(this.readString(title));
ok = true;
} catch (Exception ex) {
this.writeError("integer");
}
} while (!ok);
return input;
}
public char readChar(String title) {
char charValue = ' ';
boolean ok = false;
do {
String input = this.readString(title);
if (input.length() != 1) {
this.writeError("character");
} else {
charValue = input.charAt(0);
ok = true;
}
} while (!ok);
return charValue;
}
public void writeln() {
System.out.println();
}
public void write(String string) {
System.out.print(string);
}
public void writeln(String string) {
System.out.println(string);
}
public void write(char character) {
System.out.print(character);
}
public void writeln(int integer) {
System.out.println(integer);
}
private void writeError(String format) {
System.out.println("FORMAT ERROR! " + "Enter a " + format + " formatted value.");
}
}
ConsoleTest:
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import java.io.BufferedReader;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
public class ConsoleTest {
#Mock
private BufferedReader bufferedReader;
#InjectMocks
private Console console;
#BeforeEach
public void before(){
initMocks(this);
//this.console = new Console();
}
#Test
public void givenConsoleWhenReadStringThenValue() throws IOException {
String string = "yes";
when(this.bufferedReader.readLine()).thenReturn(string);
assertThat(this.console.readString("title"), is(string));
}
}
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
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>
<modules>
</modules>
<artifactId>solution.java.swing.socket.sql</artifactId>
<groupId>usantatecla.tictactoe</groupId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<name>${project.groupId}.${project.artifactId}</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>3.6.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>3.6.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>2.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</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>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.3</version>
<executions>
<execution>
<id>default-prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>default-report</id>
<phase>post-integration-test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>1.2.0</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.22.2</version>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>1.2.0</version>
</dependency>
</dependencies>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Thanks and greetings to the community!
I personally am not a huge fun of Mockito, I prefer to have full control of my classes using an interface and two implementations (one for production and one for test).
So this doesn't respond directly to your question about Mockito but it allows you to perfectly control the behaviour of your code without the need to use another framework.
You may define a very simple interface:
public interface Reader {
String readLine();
}
Then, you use that interface in your class Console:
public class Console {
private final Reader reader;
public Console(Reader reader) {
this.reader = reader;
}
//Replace all your this.bufferedReader.readLine() by this.reader.readLine();
}
So, in your production code you can use the real implementation with the Buffered reader:
public class ProductionReader implements Reader {
private final BufferedReader bufferedReader = new BufferedReader(...);
#Override
public String readLine() {
this.bufferedReader.readLine();
}
}
Console console = new Console(new ProductionReader());
... While in your tests you can use a test implementation:
public class TestReader implements Reader {
#Override
public String readLine() {
return "Yes";
}
}
Console console = new Console(new TestReader());
Note that while in your specific case you may mock the behaviour using Mockito, there are a lot of other cases when you will need a more complex approach and the a ove will allow you to have full control and full debuggability of your code without the need of adding any dependency.

Springcloud bus custom messages cannot be sent through rabbitmq

When using the springcloud bus, a custom message is created and sent through rabbitmq, but after the message is sent, it does not go to rabbitmq. When you try to call /actuator/bus-refresh, you can see the bus messages emitted from the console page of rabbitmq.
I tried to start a micro service to register a custom event listener but failed to receive it. However, if the sender registers a listener himself, he can receive it but does not send it from rabbitmq.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Greenwich.SR1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
About #RemoteApplicationEventScan annotations, I code all under the same package, so I should be able to scan to TestEvent. I also tried to specify basepackage.
#SpringBootApplication
#RemoteApplicationEventScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
#RestController
#RequestMapping("test")
public class TestController {
#Autowired
private ApplicationContext context;
#RequestMapping("test")
public String test() {
final TestEvent testEvent = new TestEvent(this, context.getId(), null,"test");
context.publishEvent(testEvent);
return "success";
}
}
#Data
public class TestEvent extends RemoteApplicationEvent {
private String action;
public TestEvent(Object source, String originService, String destinationService, String action) {
super(source, originService, destinationService);
this.action = action;
}
}
When I called http://localhost:8080/actuator/bus-refresh I can see the information in the rabbitmq.
{" type ":" AckRemoteApplicationEvent ", "timestamp" : 1554350325406, "originService" : "application: 0: b3461fbec3536203a7020ff9d24bb11b", "destinationService" : "* *", "id" : "e6b875bd - 2402-494 - f - a870 - 4917324 d2c5c ackId ", "" :" af93075e - 55 d2-41 f8 - ba27 - e3c80cf19eea ", "ackDestinationService" : "* *", "the event" is: "org. Springframework. Cloud. Bus. Event. RefreshRemoteApplicationEvent"}.
But when I call to http://localhost:8080/test/test, I don't.
I came into the same issue a few days ago and it turned out that it was because the originService was incorrect. passing in context.getId() as originService doesn't work.
Short answer: use org.springframework.cloud.bus.BusProperties#id. You can inject BusProperties to your component. Or you can configure your own spring cloud bus id as stated in the document.
I am not 100% sure this is the proper way. Maybe I missed something in the document. It is just based on what I read from the source code of org.springframework.cloud.bus.BusAutoConfiguration, method acceptLocal.
Hope it works for you.

Spring WebSocket integration test works at random

I have absolutely simple SpringBoot project with simple configuration and simple integration test to test WebSockets.
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>sandbox.websocket</groupId>
<artifactId>websocket</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
SpringBootApplication:
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Message broker configuration
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
#Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic");
}
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/greeting")
.withSockJS();
}
}
Integration Test to simply connect to server, subscribe to message broker and send message.
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
#DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class WebSocketIntegrationTest {
#LocalServerPort
private int localServerPort;
private BlockingQueue<String> blockingQueue;
#Before
public void setup() {
blockingQueue = new LinkedBlockingDeque<>();
}
#Test
public void shouldReceiveAMessageFromTheServer() throws Exception {
String uri = "ws://localhost:" + localServerPort + "/greeting";
WebSocketStompClient stompClient = new WebSocketStompClient(
new SockJsClient(Collections.singletonList(
new WebSocketTransport(
new StandardWebSocketClient()))));
String message = "MESSAGE TEST";
ListenableFuture<StompSession> connect = stompClient.connect(uri, new StompSessionHandlerAdapter() {});
StompSession session = connect.get(1, SECONDS);
session.subscribe("/topic", new DefaultStompFrameHandler());
session.send("/topic", message.getBytes());
Assert.assertEquals(message, blockingQueue.poll(10, SECONDS));
}
class DefaultStompFrameHandler implements StompFrameHandler {
#Override
public Type getPayloadType(StompHeaders stompHeaders) {
return byte[].class;
}
#Override
public void handleFrame(StompHeaders stompHeaders, Object o) {
System.out.println("=============================================================");
System.out.println(new String((byte[]) o));
System.out.println("=============================================================");
blockingQueue.offer(new String((byte[]) o));
}
}
}
If I run it and test it from javascript client it works like a charm.
If I run the integration test it works only sometimes. The problem is that sometimes DefaultStompFrameHandler.handleFrame() method is not called, therefore nothing is saved to the queue and assert fails.
I wrote an InboundChannel interceptor to intercept frames and print commands to the console and all four commands are allways printed (CONNECT, SUBSCRIBE, SEND, DISCONNECT).
So, all commands go to the server including SEND, but sometimes (60-70%) StompFrameHandler is not being used no matter how long the queue.poll timeout is set.
Any help, please?

How do I perform BDD test for spring application when am running the the front end using another framework (vuejs) which is running on different port

Am trying to perform BDD tests for my spring application. Am using vuejs for the front end which runs on different port.
My problem is that spring application is failing to connect to the front end application(returns 404 status)
Here is the code on how am connecting to the front end.
import static org.assertj.core.api.Assertions.assertThat;
#ContextConfiguration(classes = MainApplication.class)
#WebAppConfiguration
public class PlantRequestSteps {
List<Plant> plants = new ArrayList<>();
#Autowired
private WebApplicationContext wac;
private WebClient customerBrowser;
HtmlPage customerPage;
#Autowired
PlantHireRepository plantHireRepository;
#Before
public void setUp() {
customerBrowser = MockMvcWebClientBuilder.webAppContextSetup(wac).build();
}
#After
public void tearOff() {
plantHireRepository.deleteAll();
plants.clear();
}
#Given("^the following plants are vailable from this given date$")
public void the_following_plants_are_vailable_from_this_given_date(DataTable table){
for (Map<String, String> row: table.asMaps(String.class, String.class)){
plants.add(Plant.of(
Long.parseLong(row.get("id")), row.get("name"),
row.get("description"), new BigDecimal(row.get("price")),
LocalDate.parse(row.get("date"))));
}
}
#Given("^am on BuildIT's \"([^\"]*)\" web page$")
public void am_on_BuildIT_s_web_page(String arg1) throws Throwable {
customerPage = customerBrowser.getPage("http://localhost:8081/");
}
}
I managed to solve my problem by changing the testing library. Previously I was using HtmlUnit which only works when both the front end and back end are running on the same port(coupled together).
I used selenium and chrome driver which are independent of spring framework
Here is a basic setup ... .....
public class PlantRequestSteps {
#Autowired
private WebApplicationContext wac;
private WebDriver driver ;;
static {
// you should specify the path where you installed your chrome driver
// as the second parameter to this function
System.setProperty("webdriver.chrome.driver", "/path/chromedriver");
}
#Before
public void setup() {
driver = new ChromeDriver();
}
#After
public void tearoff() {
driver.close();
}
#Given("^ that am on this \"([^\"]*)\" web page$")
public void that_am_on_this_web_page(String arg1) throws Throwable {
driver.get("http://localhost:8081/");
}
Also do not forget to add the selenium library in addition to Junit library . Am using maveen so I added mine in the pom.xml file.
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.11.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.9.1</version>
<scope>test</scope>
</dependency>
Finally make sure you have the latest version of chrome driver installed(the old version seems not work )

Categories

Resources