WebDriverManager for PhantomJSDriver not working - maven

I cannot get WebDriverManager to work. I would like to use PhantomJSDriver without having to set a system property like this:
System.setProperty("phantomjs.binary.path", "E:/phantomjs-2.1.1-windows/bin/phantomjs.exe");
I have these dependencies in my pom.xml:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>1.5.1</version>
</dependency>
This is my code/test:
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class TestA {
WebDriver driver;
#BeforeClass
public static void setupClass() {
PhantomJsDriverManager.getInstance().setup();
}
#Before
public void setUp() {
driver = new PhantomJSDriver();
}
#Test
public void test() {
driver.get("https://www.google.de/");
System.out.println(driver.getTitle());
assertEquals("Google", driver.getTitle());
}
}
The test fails:
org.junit.ComparisonFailure: expected:<[Google]> but was:<[]>
Does anybody know what I am doing wrong? Thanks in advance!
UPDATE: Now I have another problem. Before using the webdrivermanager I had this:
DesiredCapabilities dc = DesiredCapabilities.phantomjs();
dc.setJavascriptEnabled(true);
dc.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS,
new String[] { "--web-security=no", "--ignore-ssl-errors=yes" });
System.setProperty("phantomjs.binary.path", "E:/phantomjs-2.1.1-windows/bin/phantomjs.exe");
WebDriver driver = new PhantomJSDriver(dc);
Now, when I delete the line with System.setProperty(...), it is not working anymore. Thanks for helping.

Looks like your making the assertion to early, so the page is not loaded when you call getTitle() on it. What does your println print out?
Try adding a wait to to your test, if you know the page title should be "Google" then why not wait for that to be true before doing any further assertions? When the page title is equal to what your expecting you can be reasonably confident the page is loaded. Try this:
public Boolean waitForPageIsLoaded(String title) {
return new WebDriverWait(driver, 10).until(ExpectedConditions.titleIs(title));
}

Related

add JMH an existing spring boot project

I have tried multiple tutorials to make a poc using jmh inside my test package but always faced: No matching benchmarks. Miss-spelled regexp.
My latest code:
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.35</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.35</version>
</dependency>
I downloaded 'JMH Java Microbenchmark Harness' plugin ( I tried also JMHack)
created these two classes
public class TestBenchmark
{
#Benchmark
public void init() {
// Do nothing
}
}
and
public class BenchmarkRunner {
public static void main(String[] args) throws Exception {
org.openjdk.jmh.Main.main(args);
}
}
And it's not working,
I will list couple of articles I already tried
from stackoverflow
This tutorial
medium article
I think I must create a new project but It would be great if I could apply it to an existing project
Once I did simple integration of JMH with Spring Boot, you can find an example in https://github.com/stsypanov/spring-boot-benchmark

authenticating mock user when testing in quarkus

I'm trying to test a quarkus rest-endpoint which is secured with #RolesAllowed
...
#GET
#Path("{id}")
#Produces(MediaType.APPLICATION_OCTET_STREAM)
#RolesAllowed({ "APPLICATION_USER"})
public Response getFile(#PathParam(value = "id") String documentId, #Context UriInfo uriInfo)
...
The test case
#QuarkusTest
class DocumentResourceTest {
#Test
public void testDocumentEndpoint() {
String documentId = "someId";
given()
.when().get("/documents/" + documentId)
.then()
.statusCode(200);
}
}
How can i mock an authenticated user with role 'APPLICATION_USER' for my test case ?
You can inject a SecurityIdentity which you can then stub out with the relevant role using Mockito:
#QuarkusTest
public class DocumentResourceTest {
#InjectMock
SecurityIdentity identity;
#BeforeEach
public void setup() {
Mockito.when(identity.hasRole("APPLICATION_USER")).thenReturn(true);
}
#Test
public void testDocumentEndpoint() {
String documentId = "someId";
given()
.when().get("/documents/" + documentId)
.then()
.statusCode(200);
}
}
You can of course move the stubbing call to your individual tests if you want to test a variety of different roles.
Note that you'll need to add the quarkus-junit5-mockito dependency for this to work:
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit5-mockito</artifactId>
<scope>test</scope>
</dependency>
A more convinient way to mock the security is to use Quarkus' security testing features:
https://quarkus.io/guides/security-testing#testing-security
Including
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-test-security</artifactId>
<scope>test</scope>
</dependency>
allows you to write
#Test
#TestSecurity(authorizationEnabled = false)
void someTestMethod() {
...
}
#Test
#TestSecurity(user = "testUser", roles = {"admin", "user"})
void otherTestMethod() {
...
}
In addition to the accepted answer, there is also this guide which explains how to deal with integration tests: https://quarkus.io/guides/security-oauth2#integration-testing
The first sentence there is:
If you don’t want to use a real OAuth2 authorization server for your integration tests, you can use the Properties based security extension for your test, or mock an authorization server using Wiremock.
So I think the property based security extension could also work for you: https://quarkus.io/guides/security-properties

Declarative services in OSGI

I have created a (very) simple test to determine how to send and receive events using Apache Felix.
This is my sender:
package be.pxl;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import java.util.HashMap;
#Component(name = "be.pxl.Publisher", immediate = true)
public class Publisher {
EventAdmin admin;
#Activate
public void run(Object object) {
System.out.println("IN PUBLISHER");
Event event = new Event("event", new HashMap<String, Object>());
System.out.println("\tEVENT: " + event);
admin.postEvent(event);
System.out.println("\tADMIN: " + admin);
}
#Reference(name="be.pxl.admin", service = EventAdmin.class)
protected void setEventAdmin(EventAdmin admin) {
this.admin = admin;
}
}
This is my receiver:
package be.pxl;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;
import java.util.Dictionary;
import java.util.Hashtable;
#Component(name = "be.pxl.Subscriber", immediate = true)
public class Subscriber implements EventHandler {
private BundleContext context;
#Activate
public void run(Object object) {
System.out.println("IN SUBSCRIBER");
System.out.println("\tIN RUN METHOD");
String[] topics = new String[]{"event"};
Dictionary props = new Hashtable();
props.put(EventConstants.EVENT_TOPIC, topics);
System.out.println("\t\tCONTEXT: " + context);
context.registerService(EventHandler.class.getName(), this, props);
System.out.println("\t\tCONTEXT AFTER REGISTERSERVICE: " + context);
}
public void handleEvent(Event event) {
System.out.println("IN SUBSCRIBER");
String text = event.getProperty("text").toString();
System.out.println("\tEVENT CALLED: " + text);
}
#Reference(name="be.pxl.context", service=BundleContext.class)
protected void setBundleContex(BundleContext context) {
this.context = context;
}
}
This is the pom of my sender:
<?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>be.pxl</groupId>
<artifactId>EventSender</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.service.event</artifactId>
<version>1.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.core</artifactId>
<version>6.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.service.component.annotations</artifactId>
<version>1.3.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
<version>3.2.100.v20100503</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>2.4.0</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-Vendor>SmartCampus</Bundle-Vendor>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Export-Package>
be.pxl.*;version="1.0.0"
</Export-Package>
<Import-Package>
org.osgi.service.component.annotations
org.eclipse.osgi.service
org.osgi.core
org.osgi.service.event
</Import-Package>
<_dsannotations>*</_dsannotations>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
</project>
Everything compiles fine. I create it using mvn clean package, then I install this jar file in my apache felix container and start it. However, nothing happens. Nothing get pritns out.
Thanks in advance!
You appear to be most of the way there! As you've identified, Event Admin uses a whiteboard model to receive events. The important thing is that you need to tell the whiteboard which topics you want to listen to, which you do.
%%% Update %%%
Event admin topic names use a hierarchy of tokens separated by / characters. When publishing an event you do so to a specific topic, for example foo/bar/baz. When receiving events the EventHandler will be called for topics that match its registered interest(s). These interests can either be for a specific topic, or they can end with a * to indicate a wildcard match. For example foo/bar/* would receive events sent to foo/bar/baz and events sent to foo/bar/fizzbuzz.
%%% Back to the original %%%
There are, however a couple of issues with your code:
Firstly:
#Reference(name="be.pxl.context", service=BundleContext.class)
protected void setBundleContex(BundleContext context) {
this.context = context;
}
This is not how you access the BundleContext for your bundle. If you do need a BundleContext then it should be injected as a parameter into your #Activate annotated method. A BundleContext should never be registered as a service (it represents your bundle's private access to the OSGi framework), and it would not surprise me to find that this reference is unsatisfied in your example. You don't actually need the BundleContext however because...
Secondly:
#Activate
public void run(Object object) {
System.out.println("IN SUBSCRIBER");
System.out.println("\tIN RUN METHOD");
String[] topics = new String[]{"event"};
Dictionary props = new Hashtable();
props.put(EventConstants.EVENT_TOPIC, topics);
System.out.println("\t\tCONTEXT: " + context);
context.registerService(EventHandler.class.getName(), this, props);
System.out.println("\t\tCONTEXT AFTER REGISTERSERVICE: " + context);
}
This is not the right way to write an activate method (and as a result it may not be being called), nor should you be registering your component as a service here. When you make your class an #Component it will automatically be registered as a service using each directly implemented interface. This means that:
#Component(name = "be.pxl.Subscriber", immediate = true)
public class Subscriber implements EventHandler {
...
}
is already an OSGi EventHandler service!
You can add service properties to your component using the #Component annotation, or from the OSGi R7 release (due in a couple of months) using Component Property annotations. In this case you want to set your event.topics property like this:
#Component(property="event.topics=event")
You can then get rid of the activate method completely if you like.
Finally:
Event Admin is not a message queue, and your publisher is a one-shot send. Therefore if your publisher sends the event before the handler is fully registered then it will never receive the event. Consider making the publisher send periodic events, or be certain that the receiver starts before the publisher so that you see the message.
P.S.
It's not technically a problem, but I see that you're using version 2.4 of the maven-bundle-plugin. This is very old and the current released version of bnd is 3.5.0. The Bnd team have also started providing their own Maven plugins (such as the bnd-maven-plugin) that you might want to look at.

I got Initialization error in Cucumber with maven and selenium

Test Runner
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
#CucumberOptions(features="features",glue={"stepDefinition"})
public class TestRunner {
}
MyApplication.feature
Feature: Test test smoke scenario
Scenario Outline: Test login with valid credentials
Given open fireFox and start application
When I enter valid "username" and valid "password"
Then User should be able to login successfully
Examples:
| username | password |
| 9739817000 | mnbvcxz |
| 9739817001 | mnbvcxz1 |
| 9739817002 | mnbvcxz2 |
Maven POM
<groupId>demo</groupId>
<artifactId>prac</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>prac</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.53.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.2.4</version>
</dependency>
</dependencies>
</project>
Smoke.java
public class Smoke {
WebDriver driver;
#Given("^open fireFox and start application$")
public void open_fireFox_and_start_application() throws Throwable {
driver=new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("https://testweb.com");
}
#When("^I click on Login$")
public void I_click_on_Login() throws Throwable {
driver.findElement(By.xpath("//a[contains(.,'Login')]")).click();
}
#When("^enter valid \"([^\"]*)\" and valid \"([^\"]*)\"$")
public void enter_valid_and_valid(String un, String pwd) throws Throwable {
driver.findElement(By.id("Username")).sendKeys(un);
driver.findElement(By.id("Password")).sendKeys(pwd);
}
#Then("^Click on Login$")
public void Click_on_Login() throws Throwable {
driver.findElement(By.id("loginUser")).click();
}
#Then("^User should be able to login successfully$")
public void User_should_be_able_to_login_successfully() throws Throwable {
}
These above are the test runner,feature file,Smoke test class.
Its throwing an Initilization error.I am new to Cucumber and recheck all the maven dependency ,its correct only.But even also its giving error
enter image description here
As, you have not specified any sets of data for your feature file, you do not need to use Scenario Outline. You can use it when you need to execute same scenario with different sets of data. Hence, remove Scenario Outline from your feature file (shown below the updated feature file) and retry:
Feature: Test Milacron smoke scenario
Scenario: Test login with valid credentials
Given open fireFox and start application
When I enter valid "username" and valid "password"
Then User should be able to login successfully
Please refer to link for more details about writing feature files. Let me know, if you have any further queries.
Scenario Outline is used to pass different sets of input data to your scenario. For instance 'ABC' and 'PWD' are your username, password respectively then update your feature file as below,
Feature: Test Milacron smoke scenario
Scenario Outline: Test login with valid credentials
Given open fireFox and start application
When I enter valid "username" and valid "password"
Then User should be able to login successfully
Examples:
| username | password |
| ABC | PWD |
What worked for me was to remove the empty feature files (those without any scenarios present) from the features directory.
Your pom file is absolutely fine.
Here you are using Scenario Outline if you are using Scenario outline there should be Examples annotation in the feature file. Anyways your test scenario can be achieved without using scenario outline
Update feature file and java file with below code:
Myapplication.feature:
Feature: Test test smoke scenario
Scenario: Test login with valid credentials
Given open fireFox and start application
When I click on Login
When I enter valid "username" and valid "password"
Then I click on Loginbutton
Then User should be able to login successfully
Smoke.java:
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class Smoke {
WebDriver driver;
#Given("^open fireFox and start application$")
public void open_fireFox_and_start_application() throws Throwable {
driver=new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("https://testweb.com");
}
#When("^I click on Login$")
public void I_click_on_Login() throws Throwable {
driver.findElement(By.xpath("//a[contains(.,'Login')]")).click();
}
#When("^I enter valid \"([^\"]*)\" and valid \"([^\"]*)\"$")
public void i_enter_valid_and_valid(String arg1, String arg2) throws Throwable {
driver.findElement(By.id("Username")).sendKeys(arg1);
driver.findElement(By.id("Password")).sendKeys(arg2);
}
#Then("^I click on Loginbutton$")
public void Click_on_Login() throws Throwable {
driver.findElement(By.id("loginUser")).click();
}
#Then("^User should be able to login successfully$")
public void User_should_be_able_to_login_successfully() throws Throwable {
}
}
Maintain Folder structure as mentioned in the attached image
If you want to use scenario outline update feature file like below
Same smoke.java file will works in this case.
Feature: Test test smoke scenario
Scenario Outline: Test login with valid credentials
Given open fireFox and start application
When I click on Login
When I enter valid "<username>" and valid "<password>"
Then I click on Loginbutton
Then User should be able to login successfully
Examples:
|username|password|
|test|test|
Let me know if it works for you

Mock only selected properties in Spring Environment

I want to be able to use a test properties files and only override a few properties. Having to override every single property will get ugly fast.
This is the code I am using to test my ability to mock properties and use existing properties in a test case
#RunWith(SpringRunner.class)
#SpringBootTest(classes = MyApp.class)
#TestPropertySource(
locations = { "classpath:myapp-test.properties" },
properties = { "test.key = testValue" })
public class EnvironmentMockedPropertiesTest {
#Autowired private Environment env;
// #MockBean private Environment env;
#Test public void testExistingProperty() {
// some.property=someValue
final String keyActual = "some.property";
final String expected = "someValue";
final String actual = env.getProperty(keyActual);
assertEquals(expected, actual);
}
#Test public void testMockedProperty() {
final String keyMocked = "mocked.test.key";
final String expected = "mockedTestValue";
when(env.getProperty(keyMocked)).thenReturn(expected);
final String actual = env.getProperty(keyMocked);
assertEquals(expected, actual);
}
#Test public void testOverriddenProperty() {
final String expected = "testValue";
final String actual = env.getProperty("test.key");
assertEquals(expected, actual);
}
}
What I find is:
#Autowired private Environment env;
testExistingProperty() and testOverriddenProperty() pass
testMockedProperty() fails
#MockBean private Environment env;
testMockedProperty() passes
testExistingProperty() and testOverriddenProperty() fail
Is there a way to achieve what I am aiming for?
Dependencies:
<spring.boot.version>1.4.3.RELEASE</spring.boot.version>
...
<!-- Spring -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<!-- Starter for testing Spring Boot applications with libraries including JUnit,
Hamcrest and Mockito -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${spring.boot.version}</version>
</dependency>
Ok i have made this work, you need to use Mockito to accompish what you are looking for:
Maven Dependency
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.6.4</version>
</dependency>
Test Class Set up
import static org.mockito.Mockito.*;
import static org.springframework.test.util.AopTestUtils.getTargetObject;
#RunWith(SpringRunner.class)
#SpringBootTest(classes = MyApp.class)
#TestPropertySource(
locations = { "classpath:myapp-test.properties" },
properties = { "test.key = testValue" })
public class AnswerTest {
// This will be only for injecting, we will not be using this object in tests.
#Autowired
private Environment env;
// This is the reference that will be used in tests.
private Environment envSpied;
// Map of properties that you intend to mock
private Map<String, String> mockedProperties;
#PostConstruct
public void postConstruct(){
mockedProperties = new HashMap<String, String>();
mockedProperties.put("mocked.test.key_1", "mocked.test.value_1");
mockedProperties.put("mocked.test.key_2", "mocked.test.value_2");
mockedProperties.put("mocked.test.key_3", "mocked.test.value_3");
// We use the Spy feature of mockito which enabled partial mocking
envSpied = Mockito.spy((Environment) getTargetObject(env));
// We mock certain retrieval of certain properties
// based on the logic contained in the implementation of Answer class
doAnswer(new CustomAnswer()).when(envSpied).getProperty(Mockito.anyString());
}
Test case
// Testing for both mocked and real properties in same test method
#Test public void shouldReturnAdequateProperty() {
String mockedValue = envSpied.getProperty("mocked.test.key_3");
String realValue = envSpied.getProperty("test.key");
assertEquals(mockedValue, "mocked.test.value_3");
assertEquals(realValue, "testValue");
}
Implementation of Mockito's Answer interface
// Here we define what should mockito do:
// a) return mocked property if the key is a mock
// b) invoke real method on Environment otherwise
private class CustomAnswer implements Answer<String>{
#Override
public String answer(InvocationOnMock invocationOnMock) throws Throwable {
Object[] arguments = invocationOnMock.getArguments();
String parameterKey = (String) arguments[0];
String mockedValue = mockedProperties.get(parameterKey);
if(mockedValue != null){
return mockedValue;
}
return (String) invocationOnMock.callRealMethod();
}
}
}
Try it out, and let me know if all is clear here.

Resources