t.me/atinfo_chat Telegram группа по автоматизации тестирования

Parallel test execution in Selenium Java + TestNG

framework
infrastructure
execution
parallel
java
testng
webdriver
Теги: #<Tag:0x00007fb2fbb3ed30> #<Tag:0x00007fb2fbb3ebf0> #<Tag:0x00007fb2fbb3eab0> #<Tag:0x00007fb2fbb3e970> #<Tag:0x00007fb2fbb3e808> #<Tag:0x00007fb2fbb3e6c8> #<Tag:0x00007fb2fbb3e588>

(S Stream) #1

Всем привет!
Занимаюсь автоматизацией несколько месяцев, дома на досуге пишу свой фреймворк в нерабочее время. У меня изначально инстанс WebDriver’a был статическим, т.к. я запускал каждый тест в одиночку, когда писал его и не было нужды тогда заниматься параллелизацией. Сейчас решил это исправить, уже много разных вариантов пробовал, но всеравно натыкаюсь на NPE во время параллельного запуска нескольких тестов через testng.xml.

Вот мои сниппеты:

testng.xml

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="FitSuite" parallel="methods">

  <listeners>
    <listener class-name="resources.Listeners"/>
  </listeners>

  <test name="HomePageTest">
    <classes>
      <class name="selenium.tests.HomePageTest"/>
      <class name="selenium.tests.LoginPageTest"/>
      <class name="selenium.tests.MyClassesTest"/>
</suite>

TestBase.class

public class TestBase {
  public  /*static*/ WebDriver driver;
  protected Properties properties;
  public Logger log = LogManager.getLogger(TestBase.class.getName());
  public static String propertiesFilePath =
    System.getProperty("user.dir") + "//src//main//java//resources//TestProperties.properties";

  public WebDriver initializeDriver() {

    try {
      properties = new Properties();
      properties.load(new FileInputStream(propertiesFilePath));
      String browserName = properties.getProperty("browser");

      if (browserName.equalsIgnoreCase("chrome")) {
        System.setProperty("webdriver.chrome.driver",
          System.getProperty("user.dir") + "//src//main//java//resources//chromedriver");
        driver = new ChromeDriver();
      }
      else if (browserName.equalsIgnoreCase("chrome-headless")) {
        System.setProperty("webdriver.chrome.driver",
          System.getProperty("user.dir") + "//src//main//java//resources//chromedriver");

        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("--headless");
        // chromeOptions.setHeadless(true); -- this is the same as above.
        driver = new ChromeDriver(chromeOptions);
      }
      else if (browserName.equalsIgnoreCase("firefox")) {
        System.setProperty("webdriver.gecko.driver",
          System.getProperty("user.dir") + "//src//main//java//resources//geckodriver");
        driver = new FirefoxDriver();
      }
      else driver = new SafariDriver();

    } catch (IOException e) {
      e.printStackTrace();
      log.fatal("Driver initialization has been crashed");
    }

    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(7, TimeUnit.SECONDS);
    log.info("Driver has been initialized successfully");

    return driver;
  }

  public void tearDown() {
    driver.manage().deleteAllCookies();
    driver.quit();
    driver = null;
    log.info("Driver session has been ended successfully");
  }

  public void takeScreenshot(String testResult) {
    try {
      File screenshotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
      FileUtils.copyFile(screenshotFile, new File(
        System.getProperty("user.dir") + "//ScreenshotsFailure//"
        + testResult + "__" + "failure.png"));

      log.info("Screenshot of " + testResult + "'s failure has been created successfully");
    } catch (IOException e) {
      e.printStackTrace();
      log.error("Screenshot of " + testResult + "'s failure has not been created");
    }
  }
}

HomePageTest.class


public class HomePageTest extends TestBase {
  public Logger log = LogManager.getLogger(HomePageTest.class.getName());
  private HomePage homePage;
  private SoftAssert softAssertion;
//  private WebDriver driver;


  @BeforeMethod
  void initialize() {
    driver = initializeDriver();
    log.info("Driver for " + HomePageTest.class.getName() + " has been invoked successfully");
    driver.get(properties.getProperty("baseurl"));
  }


  @Test
  void checkHomePageUI() {
    homePage = new HomePage(driver);
    softAssertion = new SoftAssert();

    softAssertion.assertEquals(homePage.getHomePageTitleReal(), homePage.getHomePageTitleExp());
    softAssertion.assertTrue(homePage.navigationBarIsDisplayed());
    softAssertion.assertTrue(homePage.faceSloganIsDisplayed());
    softAssertion.assertTrue(homePage.faceTextIsDisplayed());
    softAssertion.assertTrue(homePage.headerImageIsDisplayed());
    softAssertion.assertTrue(homePage.createAccountButtonIsDisplayed());
    softAssertion.assertTrue(homePage.loginButtonIsDisplayed());
    softAssertion.assertTrue(homePage.footerSectionIsDisplayed());
    softAssertion.assertAll();

    log.info("checkHomePageUI() Test has been performed successfully");
  }

  @Test
  void checkFooterSocialMedia() {
    homePage = new HomePage(driver);
    softAssertion = new SoftAssert();

    softAssertion.assertTrue(homePage.socialMediaButtonsCheck());
    softAssertion.assertAll();
    log.info("checkFooterSocialMedia() Test has been performed successfully");
  }

  @Test
  void checkFooterLinks() {LoginPageTest
    homePage = new HomePage(driver);
    softAssertion = new SoftAssert();

    softAssertion.assertTrue(homePage.footerLinksCheck());
    softAssertion.assertAll();
    log.info("checkFooterLinks() Test has been performed successfully");
  }


  @AfterMethod
  void closeDriver() {
//    tearDown();
    driver.quit();
  }
}

LoginPageTest.class

public class LoginPageTest extends TestBase {
  public Logger log = LogManager.getLogger(LoginPageTest.class.getName());
  private LoginPage loginPage;
  private SoftAssert softAssert;
//  private WebDriver driver;

  @BeforeMethod
  void initialize() {
    driver = initializeDriver();
    log.info("Driver for " + LoginPageTest.class.getName() + " has been invoked successfully");
    driver.get(properties.getProperty("login"));
  }

  @Test
  void loginPositive() {
    loginPage = new LoginPage(driver);
    SearchPage searchPage = new SearchPage(driver);
    softAssert = new SoftAssert();

    loginPage.enterEmail();
    loginPage.enterValidPassword();
    loginPage.clickLoginButton();
    softAssert.assertTrue(searchPage.navigationBarIsDisplayed());
    softAssert.assertTrue(searchPage.searchHeaderIsDisplayed());
    softAssert.assertTrue(searchPage.searchContentIsDisplayed());
    softAssert.assertEquals(searchPage.getTitleReal(), searchPage.getTitleExp());
    softAssert.assertAll();

    log.info("loginPositive() Test has been performed successfully");
  }

  @Test
  void loginNegative() {
    loginPage = new LoginPage(driver);
    softAssert = new SoftAssert();

    loginPage.enterEmail();
    loginPage.enterInvalidPassword();
    loginPage.clickLoginButton();

    softAssert.assertTrue(loginPage.errorPopUpIsDisplayed());
    softAssert.assertAll();

    log.info("loginNegative() Test has been performed successfully");
  }


  @AfterMethod
  void closeDriver() {
    tearDown();
  }

}

Буду очень признателен за советы более опытных коллег. Спасибо большое наперед


(Дмитрий Мирошник) #2

Пример ошибки бы ещё…