How to get the current remote webdriver instance inside onTestFailure(ITestResult) - screenshot

I want to integrate the code to take screenshot using remoteWebdriver inside, testng's onTestFailure(ITestResult). I am unable to get the current webdriver instance inside onTestFailure().

Okay, I had a similar problem.
And since there's no clear answer here, I would post my ( working) solution
On your BaseTest / TestBase class, make your RemoteWebdriver instance accessible ( either by having it as a public property or with a getter)
In the Listener class (In my case its a public property):
public class BaseTest {
public RemoteWebDriver remoteDriver;
//... initalize driver
}
public class TestListener implements ITestListener {
#Override
public void onTestFailure(ITestResult result) {
BaseTest test = (BaseTest) result.getInstance();
if (test == null) {
return;
}
RemoteWebDriver driver = test.remoteDriver;
}
}

Related

What's the purpose of By keyword in Selenium Java

Sample Code:
public class RediffLoginPage
{
Webdriver driver;
public RediffLoginPage(Webdriver driver){
this.driver=driver;
}
By username=By.xpath(".//*(#id='login1']");
By Password=By.name("passwd");
}
public Webelement Emailid()
{
return driver.findElement(username);
}
public Webelement Password(){return driver.findElement(Password);}
In this line,
By username=By.xpath(".//*(#id='login1']");
what's the purpose of first By keyword here?
It's object repository code for a testcase.
Class By
Class By extends java.lang.Object and is defined as:
public abstract class By
extends java.lang.Object
Mechanism used to locate elements within a document. In order to create your own locating mechanisms, it is possible to subclass this class and override the protected methods as required, though it is expected that all subclasses rely on the basic finding mechanisms provided through static methods of this class:
public WebElement findElement(WebDriver driver) {
WebElement element = driver.findElement(By.id(getSelector()));
if (element == null)
element = driver.findElement(By.name(getSelector());
return element;
}
By have the following direct known Subclasses:
By.ByClassName
By.ByCssSelector
By.ById
By.ByLinkText
By.ByName
By.ByPartialLinkText
By.ByTagName
By.ByXPath
By.Remotable

Testng how to get all the log steps in aftermethod for post issue on some bug tracking tools

I am working on a project where if test case is failed I have to post a bug on their bug tracking tools through the tools. But they want in a bug report all the steps should mentioned properly with error.
Like in the description they want like this
Open Url
List item
Click the submit button Dashboard title is not match properly
In My automation code, I have written log
public class logtest {
WebDriver driver;
#BeforeMethod
public void Before(){
driver=new ChromeDriver();
}
#Test
public void test1(){
Log.info("Open URl");
//Opened url
Log.info("Click on the submit button");
// Submit button Clicked
Log.info("Open Dashboard");
Log.info("Dashboard Title match");
}
#AfterMethod
public void AfterMethod(ITestResult result){
if (result.getStatus() == ITestResult.FAILURE) {
PostIssue_to_Somewhere();
}
}
}
Is there any want I can get all the steps that I print inside #Test in the after method
so I can post bugs to their board through API
I think I can save the result somewhere and print it the end of the test case but I don't think it's an ideal solution. If you have any suggestion or way that I can manage it using testing that will really helpful
You cannot get the result in after test method. you should use TestNG listener for get the results
Steps to get them :
First create your own class with extend listener class
public class Listener implements ITestListener
Then use the override method to get the results
#Override
public void onTestSuccess(ITestResult iTestResult) {
}
there are several method to get the exact data,
OnStart- OnStart method is called when any Test starts.
onTestSuccess- onTestSuccess method is called on the success of any test
onTestFailure- onTestFailure method is called on the failureof any Test.
onTestSkipped- onTestSkipped method is called on
skipped of any Test
onTestFailedButWithinSuccessPercentage- method
is called each time Test fails but is within success percentage.
onFinish- onFinish method is called after all Tests are executed.
Use Extent Report and then use its method like (log, pass, fail ) to log your steps in your report, based on your test result, if you still need help let me know :)
You can see the full project demo code at ( below is code for the extent report) https://github.com/0kakarot0/ExtentReportBasic.git
public class MyExtentReport {
private WebDriver driver;
ExtentSparkReporter spark;
ExtentReports extentReports;
ExtentTest extentTest;
public MyExtentReport(WebDriver driver) {
this.driver = driver;
}
//Created Extent Report Html File
public void extentReporter() {
Date date = new Date();
String rightNow = "Spark"+ date.getTime() + ".html" ;
String pathOfFile = "allReports/"+rightNow;
spark = new ExtentSparkReporter(pathOfFile);
extentReports = new ExtentReports();
extentReports.attachReporter(spark);
}
public void logTestNameAndDescription(String name, String description){
extentTest = extentReports.createTest(name, description);
}
public void logTestInfo(String testInfo){
extentTest.log(Status.INFO,testInfo);
}
public void logPassedTestSteps(String logPassMessage){
extentTest.pass(logPassMessage);
}
public void logFailTestSteps(String logFailMessage){
extentTest.fail(logFailMessage);
}
public void logFailTestScreenShot(String reasonOfFailure){
extentTest.fail(reasonOfFailure,MediaEntityBuilder.createScreenCaptureFromPath("utils/failedTestScreenShot/screenshot.png").build());
}
public void flushExtentReport(){
extentReports.flush();
}

Selenium PageFactory placement in framework

Currently I have the following classes which use PageFactory to initialize the elements that I use.
Base Class:
public class BaseClass {
public static WebDriver driver;
public static boolean bResult;
public BaseClass(WebDriver driver){
BaseClass.driver = driver;
BaseClass.bResult = true;
}}
Login Page Classs that holds the elements:
public class LoginPage extends BaseClass{
public LoginPage(WebDriver driver)
{
super(driver);
}
#FindBy(how= How.XPATH, using="//input[#placeholder='Username']")
public static WebElement username;
Then I use a separate Login class for my actions:
public class Login {
//Login
public static void enterUsernamePassword(String username, String password) throws Exception{
LoginPage.username.sendKeys(username);
LoginPage.password.sendKeys(password);
}
Then my steps class:
#When("^I enter a valid username (.*) and password (.*)")
public void I_enter_a_valid_username_and_password(String username, String password) throws Throwable
{
PageFactory.initElements(driver, LoginPage.class);
Login.enterUsernamePassword(username, password);
}
As you can see I am using PageFactory within the steps class. I hate doing this and would like to put the PageFactory somewhere else, just not in the steps class.
Without adding or deleting any classes, where could I place the PageFactory class? Any help would be appreciated.
I found that the best to do it is by using an Inversion Of Control / Dependency Injection framework. I use Spring but there are other options as well, e.g. Guice, Weld, Picocontainer.
Using Spring you can annotate all pages with #Component and add a PageObject Bean postprocessor to initialize all page elements when the pages are being created.
This approach is also recommended by the Cucumber for Java Book by Aslak Hellesoy (Cucumber Ltd founder). Cucumber also provides

Assertion in selenium webdriver -report showing only falied methods, not passed methods

In my selenium TestNG class, there are some
methods, like method1, method2 etc.
I have added fail and success conditions to each method.
public class TestNGClass {
public void method1(String value) throws Exception {
if(value.equals("PASS"){
org.testng.Assert.assertTrue(condition, message);
}
}
//This is another method
public void method2(String value) throws Exception {
if(value.equals("FAIL"){
org.testng.Assert.fail(message);
}
}
But after the TestNG class execution, in the Test-Output folder "Index.html" will be created, which shows only the failed methods. How to display the passed methods also (custom report) .?
Thank you
Convert your test methods using #Test annotation. Modified Code Snippet:
public class TestNGClass {
#Test
public void method1(){
Assert.assertTrue(condition, "Your Message goes here");
}
//This is another method
#Test
public void method2(){
Assert.fail("Your Message goes here");
}
Now, you will have your testcases reported.

Multiple browser windows opening automatically when one class is called in another class

I have created a class in which I am creating all the methods I require for my test automation. Issue which I am facing is that when I run main class, it works fine. But when I call that class in other class it opens 2 browser windows. The test is performed on 1 and other remains ideal. Also when I use close() or quit() method for #After, it closes the ideal window not the one which I am working on.
Below is my code snippet for ref.
Main class
public class ProjectManagement{
WebDriver driver = new FirefoxDriver();
public void navigateCreate(String uid, String pass) throws Throwable {
driver.manage().window().maximize();
driver.get(baseurl);
driver.findElement(By.id("Email")).sendKeys(uid);
driver.findElement(By.id("Password")).sendKeys(pass);
driver.findElement(By.id("loginBtn")).click();
driver.findElement(By.linkText("Projects")).click();
driver.findElement(By.linkText("Create New Project")).click();
}
}
Test Class
public class NewTest extends ProjectManagement{
ProjectManagement project1 = new ProjectManagement();
#Test
public void createPro() throws Throwable {
project1.navigateCreate(UId,Password);
}
#AfterTest
public void afterTest() {
driver.quit();
}
}
If you are extending ProjectManagement, you don't need to instantiate it on the sub-class. By doing so, you're effectively creating two instances of the class and, as such, two instances of WebDriver (which in turn generates two browser windows).
So, remove the following:
ProjectManagement project1 = new ProjectManagement();
And change your createPro() method to:
#Test
public void createPro() throws Throwable {
navigateCreate(UId,Password);
}