Я планирую запускать тесты из testng.xml с использованием appium, приложения для Android, Java, огурца, testng, объектной модели страницы. Я могу запустить приложение здесь `pom.getVisionAppLaunch(getDriver()).setupAppLaunch();'
но следующий шаг не удался
pom.getLoginPage(getDriver()).clickOnNextLiveClassroom();
БАЗОВЫЙ КЛАСС:
public class VisionBase {
// ThreadLocal to hold the Appium driver
private ThreadLocal driver = new ThreadLocal();
// Method to set the driver
protected void setDriver(AppiumDriver driver) {
this.driver.set(driver);
}
// Method to get the driver
public AppiumDriver getDriver() {
return this.driver.get();
}
ReadConfig readconfig = new ReadConfig();
public static ExtentReports extentReports;
public static ExtentTest extentTest;
public static String screenshotsSubFolderName;
public String devicename = readconfig.getDeviceName();
public String path = readconfig.getAppPath();
public String packagename = readconfig.getAppPackage();
public String activity = readconfig.getAppActivity();
public String udid = readconfig.getAppUdid();
public String url = readconfig.getAppURL();
public String email = readconfig.getAppUsername();
public String password = readconfig.getAppPassword();
@BeforeSuite(alwaysRun = true)
public void initiateExtentReports() {
extentReports = new ExtentReports();
ExtentSparkReporter sparkReporter_all = new ExtentSparkReporter("AllTests.html");
extentReports.attachReporter(sparkReporter_all);
extentReports.setSystemInfo("OS", System.getProperty("os.name"));
extentReports.setSystemInfo("Java Version", System.getProperty("java.version"));
extentReports.setSystemInfo("Testing Framework", "Cucumber");
}
@AfterSuite(alwaysRun = true)
public void generateExtentReport() {
extentReports.flush();
}
@BeforeMethod
public void setupTest(Method method) {
extentTest = extentReports.createTest(method.getName());
}
// To attach Screenshot to Extent Report
@AfterMethod(alwaysRun = true)
public void checkStatus(Method m, ITestResult result) {
if (result.getStatus() == ITestResult.FAILURE) {
String screenshotPath = null;
screenshotPath = captureScreenshot(
result.getTestContext().getName() + "_" + result.getMethod().getMethodName() + ".jpg",
(AndroidDriver)getDriver());
extentTest.addScreenCaptureFromPath(screenshotPath);
extentTest.fail(result.getThrowable());
} else if (result.getStatus() == ITestResult.SUCCESS) {
extentTest.pass(m.getName() + " is passed");
}
// extentTest.assignCategory(m.getAnnotation(Test.class).groups());
// extentTest.assignCategory(m.getAnnotation(Test.class).testName());
}
// to capture the screenshot
public static String captureScreenshot(String fileName, AndroidDriver driver) {
TakesScreenshot ts = (TakesScreenshot) driver;
File sourceFile = ts.getScreenshotAs(OutputType.FILE);
File destinationFile = new File("./reports/" + fileName);
try {
FileUtils.copyFile(sourceFile, destinationFile);
} catch (IOException e) {
e.printStackTrace();
}
return destinationFile.getAbsolutePath();
}
public static String captureScreenShotBase64(AppiumDriver driver2) {
TakesScreenshot ts = (TakesScreenshot) driver2;
return ts.getScreenshotAs(OutputType.BASE64);
}
protected void waitForElementClickability(WebElement element, AppiumDriver driver2) {
WebDriverWait wait = new WebDriverWait(driver2, Duration.ofSeconds(30));
wait.until(ExpectedConditions.elementToBeClickable(element));
}
protected void waitForSingleElementVisibility(WebElement element, AppiumDriver driver2) {
WebDriverWait wait = new WebDriverWait(driver2, Duration.ofSeconds(30));
wait.until(ExpectedConditions.visibilityOf(element));
}
}
Запуск приложения:
public class VisionAppLaunch {
protected AndroidDriver driver;
ReadConfig readconfig = new ReadConfig();
public String devicename = readconfig.getDeviceName();
public String path = readconfig.getAppPath();
public String packagename = readconfig.getAppPackage();
public String activity = readconfig.getAppActivity();
public String udid = readconfig.getAppUdid();
public String url = readconfig.getAppURL();
public String email = readconfig.getAppUsername();
public String password = readconfig.getAppPassword();
public void setupAppLaunch() {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, "UiAutomator2");
capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "14.0");
capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, devicename);
capabilities.setCapability(MobileCapabilityType.APP, path);
capabilities.setCapability(MobileCapabilityType.UDID, udid);
capabilities.setCapability("appPackage", packagename);
capabilities.setCapability("appActivity", activity);
capabilities.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, 60);
capabilities.setCapability("autoGrantPermissions", true);
try {
driver = (new AndroidDriver (new URL(url), capabilities));
System.out.println("Application launched successfully!");
}
catch (MalformedURLException e) {
e.printStackTrace();
System.err.println("Failed to create AndroidDriver. Check the URL and capabilities.");
}
}
TestNG XML:
Класс Cucumber Runner:
@CucumberOptions(
features = "src/test/resources/features/signup.feature",
dryRun = false,
snippets = CucumberOptions.SnippetType.CAMELCASE,
glue = { "stepDefinitions" },
plugin = { "pretty", "html:target/cucumber-reports.html" },
monochrome = true
)
public class TestNGRunner extends AbstractTestNGCucumberTests {
}
Диспетчер объектов страниц:
public class PageObjectManager {
private LoginPage loginPage;
private VisionAppLaunch visionAppLaunch;
public LoginPage getLoginPage(AppiumDriver driver) {
return (loginPage == null) ? loginPage = new LoginPage((AndroidDriver) driver) : loginPage;
}
public VisionAppLaunch getVisionAppLaunch(AppiumDriver driver) {
return (visionAppLaunch == null) ? visionAppLaunch = new VisionAppLaunch() : visionAppLaunch;
}
}
Класс страницы:
public class LoginPage extends VisionBase {
AppiumDriver driver;
public LoginPage(AppiumDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
@AndroidFindBy(xpath = "//android.widget.Button[@content-desc=\"Next\"]")
private WebElement liveClassroomNext;
@AndroidFindBy(xpath = "//android.widget.Button[@content-desc=\"Next\"]")
private WebElement performAnalysNext;
@AndroidFindBy(xpath = "//android.widget.Button[@content-desc=\"Next\"]")
private WebElement allIndiaPrlimsNext;
@AndroidFindBy(xpath = "//android.widget.Button[@content-desc=\"Next\"]")
private WebElement allIndiaMainsNext;
@AndroidFindBy(xpath = "//android.widget.Button[@content-desc='Continue']")
private WebElement freeResourcesContinue;
@AndroidFindBy(xpath = "(//android.widget.ImageView)[11]")
private WebElement menuAtBottom;
@AndroidFindBy(xpath = "//android.widget.Button[@content-desc=\"Login\"]")
private WebElement login;
@AndroidFindBy(xpath = "//android.widget.ScrollView/android.widget.EditText[1]")
private WebElement username;
@AndroidFindBy(xpath = "//android.widget.ScrollView/android.widget.EditText[2]")
private WebElement password;
@AndroidFindBy(xpath = "//android.view.View[@content-desc=\"Welcome Back!\"]")
private WebElement welcome;
public void clickOnNextLiveClassroom11() {
if (liveClassroomNext != null) {
System.out.println("Next class button is initialized.");
waitForElementClickability(liveClassroomNext,driver);
liveClassroomNext.click();
} else {
System.out.println("Next class button is NOT initialized.");
throw new RuntimeException("Next class button is not initialized.");
}
}
public LoginPage clickOnNextLiveClassroom() {
// Wait for a maximum of 30 seconds
waitForElementClickability(liveClassroomNext,driver);
liveClassroomNext.click();
return this;
}
public LoginPage clickOnNextLivePerformAnalyst() {
// Wait for a maximum of 30 seconds
waitForElementClickability(performAnalysNext,driver);
performAnalysNext.click();
return this;
}
public LoginPage clickOnNextAllIndiaPrlims() {
// Wait for a maximum of 30 seconds
waitForElementClickability(allIndiaPrlimsNext,driver);
allIndiaPrlimsNext.click();
return this;
}
public LoginPage clickOnNextAllIndiaMains() {
// Wait for a maximum of 30 seconds
waitForElementClickability(allIndiaMainsNext,driver);
allIndiaMainsNext.click();
return this;
}
public LoginPage clickOnContinueFreeResources() {
// Wait for a maximum of 30 seconds
waitForElementClickability(freeResourcesContinue,driver);
freeResourcesContinue.click();
return this;
}
public boolean isWelcomeDisplayedOnLoginScreen() {
// Wait for a maximum of 30 seconds for the banner text to be displayed
waitForSingleElementVisibility(welcome,driver);
welcome.click();
return welcome.isDisplayed();
}
public LoginPage clickOnMenu() {
// Wait for a maximum of 30 seconds for the banner text to be displayed
waitForElementClickability(menuAtBottom,driver);
menuAtBottom.click();
String base = captureScreenShotBase64(driver);
extentTest.addScreenCaptureFromBase64String(base, "Screenshot of login page");
return this;
}
// Entering Email Address in the Login page
public LoginPage enterUsername(String email) {
waitForSingleElementVisibility(username,driver);
username.sendKeys(email);
String val = username.getAttribute("value");
extentTest.info("Entered Email : " + val);
return this;
}
public LoginPage clickOnPasswordField() {
// Wait for a maximum of 30 seconds for the banner text to be displayed
waitForElementClickability(password,driver);
password.click();
return this;
}
// Entering password in the Login page
public LoginPage enterPassword(String pwd) {
waitForSingleElementVisibility(password,driver);
password.sendKeys(pwd);
String val = password.getAttribute("value");
extentTest.info("Entered password : " + val);
return this;
}
public LoginPage touchOnTheScreen() throws InterruptedException {
// Define the point where you want to touch the screen (modify x and y as
// needed)
Point tapPoint = new Point(400, 600);
// Create an input source for touch actions
PointerInput finger = new PointerInput(PointerInput.Kind.TOUCH, "finger");
// Create a loop to tap the screen 5 times
for (int i = 0; i < 6; i++) {
// Create a sequence to represent the tap action
Sequence tapSequence = new Sequence(finger, 1);
// Move to the tap point
tapSequence.addAction(finger.createPointerMove(Duration.ofMillis(0), PointerInput.Origin.viewport(),
tapPoint.x, tapPoint.y));
// Tap down
tapSequence.addAction(finger.createPointerDown(PointerInput.MouseButton.LEFT.asArg()));
// Tap up (to complete the tap action)
tapSequence.addAction(finger.createPointerUp(PointerInput.MouseButton.LEFT.asArg()));
// Perform the tap action
((RemoteWebDriver) driver).perform(Arrays.asList(tapSequence));
// Optionally add a small delay between taps
Thread.sleep(2000); // Adjust the sleep time as needed
}
return this;
}
public LoginPage clickOnLoginButton() {
// Wait for a maximum of 30 seconds for the banner text to be displayed
waitForElementClickability(login,driver);
login.click();
String base = captureScreenShotBase64(driver);
extentTest.addScreenCaptureFromBase64String(base, "Screenshot of login page");
return this;
}
Определения шагов:
public class Login extends VisionBase {
@Given("I launch the app")
public void iLaunchTheApp() throws MalformedURLException, InterruptedException {
PageObjectManager pom = new PageObjectManager();
pom.getVisionAppLaunch(getDriver()).setupAppLaunch();
Thread.sleep(10000);
// Click on the "Live Classroom" Next button
pom.getLoginPage(getDriver()).clickOnNextLiveClassroom();
Thread.sleep(2000);
// Click on the "Performance Analysis" Next button
pom.getLoginPage(getDriver()).clickOnNextLivePerformAnalyst();
Thread.sleep(2000);
// Click on the "All India Prelims" Next button
pom.getLoginPage(getDriver()).clickOnNextAllIndiaPrlims();
Thread.sleep(2000);
// Click on the "All India Mains" Next button
pom.getLoginPage(getDriver()).clickOnNextAllIndiaMains();
Thread.sleep(2000);
// Click on the "Free Resources" Continue button us
pom.getLoginPage(getDriver()).clickOnContinueFreeResources();
Thread.sleep(2000);
pom.getLoginPage(getDriver()).touchOnTheScreen();
}
@When("I click on the login button")
public void iClickOnTheLoginButton() throws InterruptedException {
PageObjectManager pom = new PageObjectManager();
// Click on the "Menu" at bottom
pom.getLoginPage(getDriver()).clickOnMenu();
pom.getLoginPage(getDriver()).clickOnLoginButton();
Thread.sleep(4000);
}
@Then("I should see the login page")
public void iShouldSeeTheLoginPage() throws InterruptedException {
PageObjectManager pom = new PageObjectManager();
// Click on the "Menu" at bottom
pom.getLoginPage(getDriver()).enterUsername(email);
Thread.sleep(2000);
pom.getLoginPage(getDriver()).clickOnPasswordField();
Thread.sleep(2000);
pom.getLoginPage(getDriver()).enterPassword(password);
Thread.sleep(2000);
pom.getLoginPage(getDriver()).isWelcomeDisplayedOnLoginScreen();
Thread.sleep(2000);
pom.getLoginPage(getDriver()).clickOnLoginButton();
Thread.sleep(2000);
}
}
pom-файл:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
FlutterVisionpp
FlutterVisionApp
0.0.1-SNAPSHOT
org.seleniumhq.selenium
selenium-java
4.9.1
io.cucumber
cucumber-picocontainer
7.15.0
io.appium
java-client
8.3.0
org.testng
testng
7.8.0
test
io.cucumber
cucumber-java
7.15.0
io.cucumber
cucumber-testng
7.15.0
com.aventstack
extentreports
5.1.1
org.apache.poi
poi
5.2.3
org.apache.poi
poi-ooxml
5.2.3
com.googlecode.json-simple
json-simple
1.1.1
org.apache.logging.log4j
log4j-api
2.19.0
org.apache.logging.log4j
log4j-core
2.19.0
Файл свойств:
deviceName=Moto g24
appPath=E:\\Eclipse\\FlutterVisionApp\\src\\test\\resources\\apps\\app-release.apk
appPackage=com.makemytrip.app
appActivity=com.makemytrip.app.MainActivity
udid=ZD222LFXGS
url=http://127.0.0.1:4723/wd/hub
Подробнее здесь: https://stackoverflow.com/questions/791 ... -session-r
Org.openqa.selenium.SessionNotCreatedException: не удалось начать новый сеанс. Код ответа 404 ⇐ Android
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение