Appium not recognising the elements - selenium

I am experiencing a weird problem in object identification. I have 3 fields username, password and login buttons. The username field is recognised and I am able to key in the data. But Appium is not recognising the other 2 fields no matter what. I need help.
public class LoginPageObjects {
#AndroidFindBy(uiAutomator = "new UiSelector().text(\" Employee ID or Email\")")
private AndroidElement username;
#AndroidFindBy(uiAutomator = "new UiSelector().text(\"Password\")" )
private AndroidElement password;
#AndroidFindBy(uiAutomator = "new UiSelector().text(\"LOGIN\")")
private AndroidElement loginsubmit;
public AndroidElement getUsername() {
return username;
}
public AndroidElement getPassword() {
return password;
}
public AndroidElement getLoginsubmit() {
return loginsubmit;
}
}
public class LoginPageFuncs extends LoginPageObjects {
private AndroidDriver driver;
public LoginPageFuncs(AndroidDriver driver) {
this.driver = driver;
PageFactory.initElements(new AppiumFieldDecorator(driver), this);
}
public void doLogin(Map<String, String> table) throws InterruptedException {
getUsername().sendKeys(table.get("username"));
getPassword().sendKeys(table.get("password"));
getLoginsubmit().click();
}
}
<dependencies>
<dependency>
<groupId>io.appium</groupId>
<artifactId>java-client</artifactId>
<version>5.0.4</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.8.1</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.13.1</version>
</dependency>
</dependencies>

Maybe it's because of spaces with text you are trying to get.
Try this:
public class LoginPageObjects {
#AndroidFindBy(uiAutomator = "new UiSelector().textContains(\" Employee ID or Email\")")
private AndroidElement username;
#AndroidFindBy(uiAutomator = "new UiSelector().textContains(\"Password\")" )
private AndroidElement password;
#AndroidFindBy(uiAutomator = "new UiSelector().textContains(\"LOGIN\")")
private AndroidElement loginsubmit;
public AndroidElement getUsername() {
return username;
}
public AndroidElement getPassword() {
return password;
}
public AndroidElement getLoginsubmit() {
return loginsubmit;
}
}

Related

Null Pointer Exception in POST method in jersey

I am building a web project using jersey and hibernate. I am testing crud operations in postman. For POST method i get a null pointer exception and I don't know how to solve. Please help me. I am new in jersey.
Below is my code and my full stack trace.
BookRepository.com
package com.bookstrore.repository;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Transaction;
import org.hibernate.Session;
import org.hibernate.Query;
import com.bookstrore.model.Book;
import com.bookstrore.model.SessionUtil;
//import com.pluralsight.model.User;
public class BookRepositoryStub {
public void createBook(Book book) {
Session session = SessionUtil.getSession();
Transaction tx = session.beginTransaction();
createBook(session,book);
tx.commit();
session.close();
}
private void createBook(Session session, Book bo){
Book book=new Book();
book.setBook_id(bo.getBook_id());
book.setBook_title(bo.getBook_title());
book.setBook_author(bo.getBook_author());
book.setBook_description(bo.getBook_description());
book.setBook_price(bo.getBook_price());
session.save(book);
}
public List<Book> getBooks(){
Session session = SessionUtil.getSession();
Query query = session.createQuery("from Book");
List<Book> books = query.list();
session.close();
return books;
}
public int delete(int book_id){
Session session = SessionUtil.getSession();
Transaction tx = session.beginTransaction();
String hql = "delete from Book where book_id = :book_id";
Query query = session.createQuery(hql);
query.setInteger("book_id",book_id);
int rowCount = query.executeUpdate();
System.out.println("Rows affected: " + rowCount);
tx.commit();
session.close();
return rowCount;
}
public int update(int book_id, Book bo){
if(book_id <=0)
return 0;
Session session = SessionUtil.getSession();
Transaction tx = session.beginTransaction();
String hql = "update Book set book_title = :book_title, book_author = :book_author, book_description = :book_description, book_price = :book_price, where book_id = :book_id";
Query query = session.createQuery(hql);
query.setInteger("book_id", book_id);
query.setString("book_title",bo.getBook_title());
query.setString("book_author",bo.getBook_author());
query.setString("book_description",bo.getBook_description());
query.setInteger("book_price",bo.getBook_price());
int rowCount = query.executeUpdate();
System.out.println("Rows affected: " + rowCount);
tx.commit();
session.close();
return rowCount;
}
}
BookResource.java
package com.bookstrore;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import com.bookstrore.model.Book;
//import com.ebook.model.User;
//import com.ebook.repository.BookRepository;
import com.bookstrore.repository.BookRepositoryStub;
#Path("books")
public class BookResource {
//private BookRepository bookRepository=new BookRepositoryStub();
#GET
#Produces("application/json")
public List<Book> getBook() {
BookRepositoryStub book = new BookRepositoryStub();
List books = book.getBooks();
return books;
}
#DELETE
#Path("{bookId}")
#Consumes("application/json")
public Response delete(#PathParam("bookId") int book_id){
BookRepositoryStub book = new BookRepositoryStub();
int count = book.delete(book_id);
if(count==0){
return Response.status(Response.Status.BAD_REQUEST).build();
}
return Response.ok().build();
}
#PUT
#Path("{bookId}")
//#Consumes(MediaType.APPLICATION_JSON)
#Consumes("application/json")
public Response update(#PathParam("bookId") int book_id, Book bo){
BookRepositoryStub book = new BookRepositoryStub();
int count = book.update(book_id, bo);
if(count==0){
return Response.status(Response.Status.BAD_REQUEST).build();
}
return Response.ok().build();
}
#POST
#Path("book")
#Consumes("application/json")
//#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response createBook(Book bo){
bo.setBook_title(bo.getBook_title());
bo.setBook_author(bo.getBook_author());
bo.setBook_description(bo.getBook_description());
bo.setBook_price(bo.getBook_price());
BookRepositoryStub book = new BookRepositoryStub();
book.createBook(bo);
return Response.ok().build();
}
}
Book.java
package com.bookstrore.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="book")
public class Book {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int book_id;
#Column
private String book_title;
#Column
private String book_author;
#Column
private String book_description;
#Column
private int book_price;
public int getBook_id() {
return book_id;
}
public void setBook_id(int book_id) {
this.book_id = book_id;
}
public String getBook_title() {
return book_title;
}
public void setBook_title(String book_title) {
this.book_title = book_title;
}
public String getBook_author() {
return book_author;
}
public void setBook_author(String book_author) {
this.book_author = book_author;
}
public String getBook_description() {
return book_description;
}
public void setBook_description(String book_description) {
this.book_description = book_description;
}
public int getBook_price() {
return book_price;
}
public void setBook_price(int book_price) {
this.book_price = book_price;
}
}
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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.bookstore</groupId>
<artifactId>BookStore</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>BookStore</name>
<build>
<finalName>BookStore</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<inherited>true</inherited>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<!-- use the following artifactId if you don't need servlet 2.x compatibility -->
<!-- artifactId>jersey-container-servlet</artifactId -->
<version>2.22.1</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.10.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
</dependencies>
<properties>
<jersey.version>2.22.1</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- This web.xml file is not required when using Servlet 3.0 container,
see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html -->
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.bookstrore</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/webapi/*</url-pattern>
</servlet-mapping>
</web-app>
Stack Trace:
<pre>java.lang.NullPointerException
com.bookstrore.BookResource.createBook(BookResource.java:72)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)
org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)
org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:160)
org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326)
org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
org.glassfish.jersey.internal.Errors.process(Errors.java:315)
org.glassfish.jersey.internal.Errors.process(Errors.java:297)
org.glassfish.jersey.internal.Errors.process(Errors.java:267)
org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:471)
org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:425)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:383)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:336)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:223)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
</pre>
I am looking forward for your help! Please! Thank you!
I believe that there are two problems in your code that by changing them, your problem will be solved.
First of all, in your class "Book" you need to write the constructor with all the parameters, besides the id (that is auto-generated by hibernate), and also have a no-argument constructor. So add this:
And on the other hand, you have to declare your class "Book" as #XmlRootElement as you did with #Entity and #Table.
This video explains the why of all of this and it is also a great tutorial for beginners with web services and jersey:
https://www.youtube.com/watch?v=BaZdlJSts5A&list=PLqq-6Pq4lTTZh5U8RbdXq0WaYvZBz2rbn&index=14
Hope this helps! Your Book class should look like this:
#Entity
#Table(name="book")
#XmlRootElement
public class Book {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int book_id;
#Column
private String book_title;
#Column
private String book_author;
#Column
private String book_description;
#Column
private int book_price;
public Book(){ }
public Book(String title, String author, String description, int price){
book_title = title;
book_author = author;
book_description = description;
book_price = price;
}
public int getBook_id() {
return book_id;
}
public void setBook_id(int book_id) {
this.book_id = book_id;
}
public String getBook_title() {
return book_title;
}
public void setBook_title(String book_title) {
this.book_title = book_title;
}
public String getBook_author() {
return book_author;
}
public void setBook_author(String book_author) {
this.book_author = book_author;
}
public String getBook_description() {
return book_description;
}
public void setBook_description(String book_description) {
this.book_description = book_description;
}
public int getBook_price() {
return book_price;
}
public void setBook_price(int book_price) {
this.book_price = book_price;
}
}

Could not initialize class org.eclipse.persistence.jaxb.BeanValidationHelper while trying to get JSON response

I am making application using JAVA EE,JAX-RS,JPA,GLASSFISH. Response is working properly in case of MediaType.APPLICATION_XML. It's not working in MediaType.APPLICATION_JSON.
Here is my pojo class
#Entity
#XmlRootElement
public class Book {
private int id;
private String name;
private String publication;
private String price;
#Id
#Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Basic
#Column(name = "publication")
public String getPublication() {
return publication;
}
public void setPublication(String publication) {
this.publication = publication;
}
#Basic
#Column(name = "price")
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Book book = (Book) o;
if (id != book.id) return false;
if (name != null ? !name.equals(book.name) : book.name != null) return false;
if (publication != null ? !publication.equals(book.publication) : book.publication != null) return false;
if (price != null ? !price.equals(book.price) : book.price != null) return false;
return true;
}
#Override
public int hashCode() {
int result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (publication != null ? publication.hashCode() : 0);
result = 31 * result + (price != null ? price.hashCode() : 0);
return result;
}
}
Here is the pom.xml file.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.rajesh</groupId>
<artifactId>Library</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
Resource class for endpoint
#Path("books")
public class BookResource {
#GET
#Path("{bookId}")
#Produces({MediaType.APPLICATION_JSON})
public Response getBookById(#PathParam("bookId") int id) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("abc");
EntityManager entityManager = entityManagerFactory.createEntityManager();
Book book = entityManager.find(Book.class, id);
if (book == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
return Response.status(Response.Status.OK).entity(book).build();
}
}
This is a bug in Glassfish: https://github.com/javaee/glassfish/issues/21440
It probably won't be fixed, you should switch to http://www.payara.fish/ which is patched and updated version of Glassfish (has even commercial support if needed).
This bug is fixed in Payara.
Place the "org.eclipse.persistence.moxy.jar" into
$GLASSFISHINSTALL/glassfish/modules
Then restart the glassfish
Problem had been occurred due to version of Glassfish 4.1.1.It appears there is a bug in Eclipse Link . I am using Glassfish 4.1.0 for temporary solution.
I had the same error, but my mistake was pretty funny.
I had my pom.xml pointing to EE7 API as follows:
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
Meanwhile, I forgot that Glassfish 4.x implements EE6 not EE7....
I downloaded Eclipse Glassfish 5.1.0 then I was sorted!

Jackson #Deserializer doesn't work

This is a duplicated question of this
POJO
#Entity
#Table(name = "pet")
public class Pet {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long petId;
private String petName;
private Date birthday;
#JsonSerialize(using = Serializer.class)
public Date getBirthday() {
return birthday;
}
#JsonDeserialize(using = Deserializer.class)
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Long getPetId() {
return petId;
}
public void setPetId(Long petId) {
this.petId = petId;
}
public String getPetName() {
return petName;
}
public void setPetName(String petName) {
this.petName = petName;
}
}
Serializer
public class Serializer extends JsonSerializer<Date> {
#Override
public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
System.out.println("Serializer");
}
}
Deserializer
public class Deserializer extends JsonDeserializer<Date> {
#Override
public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
System.out.println("Deserializer works.");
return new Date();
}
}
Maven Dependency
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.3.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.3.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.3.2</version>
</dependency>
update: controller code
#Transactional
#Controller
public class Demo {
#Resource
private Dao dao;
#ResponseBody
#RequestMapping("/test")
public String tester(Pet pet){
dao.saveOrUpdate(pet);
return "success";
}
#ResponseBody
#RequestMapping("/test2")
public List<Pet> tester2(){
List<Pet> pets = dao.query(Pet.class);
return pets;
}
}
however only Serializer will be invoked everytime, Deserializer doesn't take any effect, I can't see where is wrong, could anybody help me?
Thanks.

Can't publish in cometd channel

I'm getting this error when I try to publish a string in a channel:
java.lang.AbstractMethodError: org.cometd.client.BayeuxClient$BayeuxClientChannel.publish(Ljava/lang/Object;)V
this is the code that is trying to publish:
public class EnviadorMensagem implements Runnable {
private String nomeCanal;
private Mensagem mensagem;
private ClientSession cliente;
private boolean pausado = true;
private boolean cancelado = false;
#Override
public void run() {
while (pausado) {
pausar();
}
if (!cancelado) {
converterEEnviar();
}
}
private void pausar() {
synchronized (this) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void converterEEnviar() {
ConversorMensagem conversor = new ConversorMensagem();
ClientSessionChannel canal = cliente.getChannel(nomeCanal);
canal.publish(conversor.converter(mensagem)); //<- the error happens here!!
}
public void ativar() {
synchronized (this) {
pausado = false;
this.notifyAll();
}
}
public void cancelar() {
synchronized (this) {
cancelado = true;
}
ativar();
}
public void setNomeCanal(String nomeCanal) {
this.nomeCanal = nomeCanal;
}
public void setMensagem(Mensagem mensagem) {
this.mensagem = mensagem;
}
public void setCliente(ClientSession cliente) {
this.cliente = cliente;
}
}
As you can see, this class is running in a separate thread.
this is part of my pom.xml:
<dependencies>
<dependency>
<groupId>org.cometd.java</groupId>
<artifactId>cometd-java-client</artifactId>
<version>2.5.1</version>
</dependency>
<dependency>
<groupId>org.cometd.java</groupId>
<artifactId>bayeux-api</artifactId>
<version>2.5.1</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-client</artifactId>
<version>8.1.7.v20120910</version>
</dependency>
</dependencies>
Someone knows how to solve it??
You get AbstractMethodError when you compiled your code against a version of a library, but at runtime you are using another, that does not have that method, or has it with a different signature.
Double check your classpath and the CometD library versions you're using.

Allure. How to get screenshot on testFailure event. Use Java+Junit4+Maven

If I want to get screenshot when my Tests are failed, so what the best practice is? I try to do this next way:
1)overridre AllureRunListener:
public class SimpleScreenshotTestListener extends AllureRunListener{
#Override
public void testFailure(Failure failure) {
if (failure.getDescription().isTest()) {
fireTestCaseFailure(failure.getException());
} else {
startFakeTestCase(failure.getDescription());
fireTestCaseFailure(failure.getException());
finishFakeTestCase();
}
makeScreenshot("Failure screenshot");
}
}
The method makeScreenshot("Failure screenshot") is a static method in Util Class:
public final class Util {
private Util() {}
#Attachment(value = "{0}", type = "image/png")
public static byte[] makeScreenshot(String name) {
return ((TakesScreenshot) <Thread Local Driver>).getScreenshotAs(OutputType.BYTES);
}
}
3) In my pom file I use created listener
SimpleScreenshotTestListener:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<testFailureIgnore>false</testFailureIgnore>
<argLine>
-javaagent:${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar
</argLine>
<properties>
<property>
<name>listener</name>
<value>cms.fireFox.Tps.SimpleScreenshotTestListener</value>
</property>
</properties>
</configuration>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
</dependencies>
</plugin>
And my question is : Is this way is the best way or should I do this easier.
Just use JUnit Rules like the following:
public class ScreenshotOnFailureRule implements TestRule {
public Statement apply(final Statement statement, final Description description) {
return new Statement() {
#Override
public void evaluate() throws Throwable {
try {
statement.evaluate();
} catch (Throwable t) {
captureScreenshot();
throw t;
}
}
#Attachment
private byte[] captureScreenshot() {
try {
return ((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES);
} catch (Exception e) {
// No need to crash the tests if the screenshot fails
}
}
};
}
}
So far as captureScreenshot() method is run on failure Allure will attach resulting PNG byte stream to test case. Further reading about rules.