Home > database >  how to get rid of redundant code in java?
how to get rid of redundant code in java?

Time:10-10

Good Morning I create a project with tests in Selenium 4.5.0 and Java, but I have one question about change with redundant code.

I have maybe 15 files with Test in everyone file I have a setup the method with the same element (you can see in my code). How I can this method - setup and var like WebDriver driver set in other files, and use this in all my files.

My Code:

public class MyPageTest {
    WebDriver driver;
    LoginPage loginPage;
    HomePage homePage;

@BeforeEach
public void setup(){
    System.setProperty("webdriver.chrome.driver","src/main/resources/chromedriver");
    driver = new ChromeDriver();
    loginPage = PageFactory.initElements(driver, LoginPage.class);
    homePage = PageFactory.initElements(driver, HomePage.class);
    driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(20));
    driver.manage().window().maximize();
    driver.get("mysite");
}

@Test
public void badPassword(){
    loginPage.setUsername("superuser");
    loginPage.setPassword("passwwitherror");
    loginPage.clickSave();
    homePage.checkTitle();
    loginPage.checkButton();
}

@AfterEach
public void tearDown(){
    this.driver.quit();
}

}

I would like in

@BeforeEach set for example:

@BeforeEach
public void setup(){
       SetupClass.setup();
}

Thanks for your help

CodePudding user response:

You can use inheritance - extract the common variables and code into the parent class. For example:

abstract class BaseSeleniumTest {

    WebDriver driver;
    LoginPage loginPage;
    HomePage homePage;

    public BaseSeleniumTest() {
        System.setProperty("webdriver.chrome.driver","src/main/resources/chromedriver"    );
        this.driver = new ChromeDriver();
        this.loginPage = PageFactory.initElements(driver, LoginPage.class);
        this.homePage = PageFactory.initElements(driver, HomePage.class);
    }

    public void setup() {
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(20));
        driver.manage().window().maximize();
        driver.get("mysite");
    }

}

public class MyPageTest extends BaseSeleniumTest {

    @BeforeEach
    public void setup(){
        super.setup();
    }
    
}

If Selenium allows parent classes to contain annotated methods than you can simplify it to annotate the setup method in parent class and remove @BeforeEach method in child classes

CodePudding user response:

Thanks for your help everything work good :). Only my comment for variable in BaseSeleniumTest:

We need a public variable for example: public WebDriver driver; public LoginPage loginPage;

  • Related