Please help to improve my code. I use JUnit and PageObjectPattern.
I need to:
in area find email that contains String ("Test"), test fails if email not found
click on this email and find there Text ("Success")
Page:
#FindBy(className = "123")
WebElement area;
#FindBy(xpath = "//*[contains(text(), 'Test')]")
WebElement email;
public String findText(){
return area.getText();
}
public void clickEmail(){
email.click();
}
Test:
#Test
public void goTest() {
home = new Home(driver);
Assert.assertTrue("Failed", home.findText().contains("Test"));
home.clickEmail();
assertTrue(home.getElement().contains("Success"));
}
I get an error: org.openqa.selenium.ElementNotVisibleException: element not visible
Related
I am facing a problem with registration and login flow where it is required to generate an email and get token for verification. I need a service which allows user to generate n numbers of disposable emails with email data access that can self-destructs max 24 hours. Could anyone please share the service code to use in selenium java automation?
The QA teams leave such tasks for manual testing instead of writing automation tests for these scenarios. \
But, all communication from the email can be automated by the disposable email service. This article will describe how to use this service within the automation suite using Nightwatch.js (Node).
Registration and Login automation
You can use this code as well to automate such things:
2. Write down the logic of getEmail in common-function class and add dependencies in pom.xml file :
<dependency>
<groupId>com.mashape.unirest</groupId>
<artifactId>unirest-java</artifactId>
<version>1.4.9</version>
</dependency>
We will use Unirest for handling the Mail7 API code. it is a set of lightweight HTTP libraries available in multiple languages, built and maintained by Mashape, who also maintain the open-source API Gateway Kong.
Create a mail7.java file with below code
import org.apcahe.commons.lang3.RandomStringUtils;
public class mail7{
private static final String EMAIL-DOMAIN = ‘mail.io’;
private static final String EMAIL_APIKEY = ‘mail7_api_key’;
private static final String EMAIL_APISecret = ‘mail7_api_secret’;
private String emailid;
public usernameGenerator(){
String username = RandomStringUtils.randomAlphanumeric(8).toLowerCase();
System.out. println(“Random Username is ” + username);
return username;
}
public getInbox(String username){
HttpResponse <String> httpResponse = Unirest.get(“"https://api.mail7.io/inbox?apikey=" + EMAIL_APIKEY + "&apisecret=" + EMAIL_APISecret + "&to=" + username”)
.asString();
System.out.println( httpResponse.getHeaders().get("Content-Type"));
System.out.println(httpResponse.getBody());
return httpResponse.getBody();
}
3. Create a class file for Test Script of Register and Login event :
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class TestEmail throws IOException, UnirestException
{
public static void main(String[] args) {
//create a Selenium WebDriver instance
System.setProperty("webdriver.gecko.driver","dir_path\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//launch the Firefox browser and navigate to the website
driver.get(“YOUR_TEST_URL");
//puts an implicit wait for 10 seconds before throwing exceptions
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//locate the email field
WebElement email = driver.findElement(By.xpath("//input[#type='email']"));
// create a random email address
String username = usernameGenerator();
String emailID = username.concat(“#”+EMAIL_DOMIAN);
//set the field's value
email.sendKeys(emailID);
//locate the password field
WebElement password = driver.findElement(By.xpath("//input[#type='password']"));
//set the password's value
password.sendKeys("password");
//locate and click the submit button
driver.findElement(By.xpath("//input[#type='submit']")).click();
//check if the mail has been received or not
String response = getInbo(username );
if(response.isEmpty()) {
System.out.println("Test not passed");
}else {
System.out.println("Test passed");
}
//close the Firefox browser.
driver.close();
}
}
}
}
I am trying to create a framework(Selenium+TestNg+java) for a Web app(The environment is MacOs+ChromeDriver and the driver server is in \usr\local\bin) but got stuck in basic structure. I have a class(Driversetup.java) that starts the browser, another one that contains WebElements and methods(ProfileUpdateObjects.java) and the third one containing test methods. Now, when I try to run this TestNG class having just a single method, I get following exception.
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at org.openqa.selenium.support.PageFactory.instantiatePage(PageFactory.java:138).
Below is the code (All the classes are in different packages).
public class ProfileUpdateTest {
#Test(enabled = true, priority = 1)
public void profileUpdate() throws MalformedURLException, InterruptedException, ParseException {
WebDriver driver = DriverSetup.startBrowser("chrome");
ProfileUpdateObjects pu = PageFactory.initElements(driver, ProfileUpdateObjects.class);
pu.navigateProfile();
}
}
The code for ProfileUpdateObject class
public class ProfileUpdateObjects {
WebDriver driver;
public ProfileUpdateObjects(WebDriver cdriver) {
this.driver = cdriver;
}
#FindBy(xpath = " //div[#class='ico-menu']")
private WebElement menu;
#FindBy(xpath = "//a[#title='My Dashboard']")
private WebElement myDashboard;
#FindBy(xpath = " //a[contains(text(),'View Profile')]")
public WebElement profile;
#FindBy(xpath = "//li[contains(text(),'Permanent Address')]")
private WebElement permanentAddress;
#FindBy(xpath = "//li[contains(text(),'Banking Information')]")
private WebElement bankingInformation;
WebDriverWait waitfor = new WebDriverWait(driver, 2000);
public void navigateProfile() throws InterruptedException {
menu.click();
profile.click();
waitfor.until(ExpectedConditions.visibilityOf(permanentAddress));
}
}
DriverSetup.java
public class DriverSetup {
public static WebDriver driver;
public static WebDriver startBrowser(String browserName, String url) {
if (browserName.equalsIgnoreCase("chrome")) {
driver = new ChromeDriver();
}
driver.manage().window().maximize();
driver.get(url);
return driver;
}
}
It is failing in pu.navigateProfile() call. Also, is it true that #FindBy takes more memory compared to driver.find() syntax and besides POM are there any other design principles for Automation framework because most of the resources over Web are one or the other implementation of POM.
Simple solution is to move new WebDriverWait. It should not be instantiated as instance variable.
Instead of:
WebDriverWait waitfor = new WebDriverWait(driver, 2000);
public void navigateProfile() throws InterruptedException {
menu.click();
profile.click();
waitfor.until(ExpectedConditions.visibilityOf(permanentAddress));
}
Use:
public void navigateProfile() {
menu.click();
profile.click();
new WebDriverWait(driver, 2000).until(ExpectedConditions.visibilityOf(permanentAddress));
}
This will solve your issue (Already tested it)
I am trying to generate Extent Report in selenium. I have written the exact code for generating report , but the folder in which the report must be saved is empty, I have refreshed the project as well but still not able to produce report.Please let me know if I have done any thing wrong in the coding part. Here is my code:
public class ContactUsTestCase {
ExtentHtmlReporter htmlReporter;
ExtentReports extent;
ExtentTest test;
static WebDriver driver;
UtilityMethods util = new UtilityMethods();
#BeforeClass
public void launchBrowser() {
driver = UtilityMethods.openBrowser(Constants.BROWSER_NAME);
UtilityMethods.launchWebsite(Constants.URL);
}
#BeforeTest
public void startReport() {
htmlReporter = new ExtentHtmlReporter("D:\\ExtentReport");
extent = new ExtentReports();
extent.attachReporter(htmlReporter);
extent.setSystemInfo("OS", "win 10");
extent.setSystemInfo("Host Name", "Stewart");
extent.setSystemInfo("Environment", "Chrome");
htmlReporter.config().setDocumentTitle("Automation testig report");
htmlReporter.config().setReportName("Your Logo Report Name");
htmlReporter.config().setTestViewChartLocation(ChartLocation.TOP);
htmlReporter.config().setTheme(Theme.DARK);
}
#Test(priority = 1)
public void ContactUs() {
test = extent.createTest("ContactUs", "This wil check status for Conatct us page");
// util.clickElement(Constants.OPEN_CONTACTUS);
driver.findElement(By.id("email")).sendKeys("stewart****#yahoo.com");
driver.findElement(By.id("pass")).sendKeys("******");
driver.findElement(By.xpath("//input[#value='Log In']")).click();
test.log(Status.PASS, MarkupHelper.createLabel("PASS", ExtentColor.GREEN));
}
#AfterClass
public void teardown() {
extent.flush();
}
}
You have mentioned the folder name alone. Change this line
htmlReporter = new ExtentHtmlReporter("D:\\ExtentReport");
in your code to
htmlReporter = new ExtentHtmlReporter("D:\\ExtentReport\\nameOfTheReport.html");
You have missed extension for html report,
Your path should be "D:\\Demo_ExtentReport.html"
TESTDRESS
TESTDRESS
TESTDRESS is found in various place in the page.
This is one which shows link.
#FindBy(how = How.CSS,using = "a[href='test.aspx']")
link is not click
CacheLookup
#FindBy(how = How.CSS,using = "a[href='test.aspx']")
WebElement testlink;
public void ClickDress()
{
System.out.println("testlink"+testlink);
testlink.click();
}
CALLIING CODE:
Dashboardpage= PageFactory.initElements(driver, DashboardPage.class);
Dashboardpage.ClickDress();
ERROR:
Marionette INFO New connections will no longer be accepted
As you have mentioned TESTDRESS is found in various place in the page but while formatting the HTML you have stripped off the parent node id and <span> tags. So assuming that the href attributes are unique for each node the following should work:
#FindBy(how = How.CSS,using = "a[href='test.aspx?id=1']")
#CacheLookup
WebElement testlink;
public void ClickDress()
{
System.out.println("testlink"+testlink);
testlink.click();
}
and
#FindBy(how = How.CSS,using = "a[href='test.aspx?id=2']")
#CacheLookup
WebElement testlink;
public void ClickDress()
{
System.out.println("testlink"+testlink);
testlink.click();
}
I am running a test using selenium WebDriver and getting following error:
org.openqa.selenium.NoSuchWindowException: no such window: target window already closed
from unknown error: web view not found
(Session info: chrome=50.0.2661.102)
The code I wrote is:
#Test
public void LogIn_Page() throws InterruptedException {
driver.get(config.getApplicationUrl());
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
System.out.println("========== Login Test Start =========");
login.loginAction("username", "password");
}
public class LogIn_Page {
static WebDriver driver;
#FindBy(how = How.CLASS_NAME, using = "button-login")
public WebElement buttonLogin;
#FindBy(how = How.CSS, using = "input[class='is-text']")
public WebElement userName;
#FindBy(how = How.NAME, using = "j_password")
public WebElement passWord;
#FindBy(how = How.CSS, using = "button[class='login__button']")
public WebElement submit;
#FindBy(how = How.ID, using = "login-popup")
public WebElement loginPop;
public LogIn_Page(WebDriver driver) {
this.driver = driver;
}
public void loginAction(String UserName, String PassWord) {
buttonLogin.click();
userName.sendKeys(UserName);
passWord.sendKeys(PassWord);
submit.click();
}
}
The test I want to do:
Press the login button which creates a log in popup window
Enter email, password,
Press login.
The popup window appear, but the values of email and password not written (exception attached)