Use same web driver throughout selenium suite

这一生的挚爱 提交于 2019-11-28 02:06:44
lukeis

I'm not great with JUnit... looks like you're trying the solution suggested here: Before and After Suite execution hook in jUnit 4.x

which would suggest you should move your @BeforeClass into your SeleniumTestSuite class.

This is how I did it. In SeleniumTestSuite, I added a static WebDriver and instantiate it in a setUp() method annotated with @BeforeClass. Then, in the Base class that all of my selenium tests inherit from, I added a getDriver() method, that will try to get the static driver from SeleniumTestSuite. If that driver is null, then a new one gets instantiated and returned. Thus, when the selenium test classes are running via the suite, they will use the driver from SeleniumTestSuite, and when they are running individually, they will use their own driver.

SeleniumTestSuite:

@RunWith(Suite.class)
@SuiteClasses({
    AbcSeleniumTest.class,
    XyzSeleniumTest.class
})
public class SeleniumTestSuite {

    private static WebDriver driver;

    @BeforeClass
    public static void setUp() {
        driver = new FirefoxDriver();
    }

    //driver getter/setter

}

BaseSeleniumTest:

public abstract class BaseSeleniumTest {

    public WebDriver getDriver() {
        WebDriver driver = SeleniumTestSuite.getDriver();
        if(driver != null) {
            return driver;
        }

        return new FirefoxDriver();
    }

}

AbcSeleniumTest:

public class AbcSeleniumTest extends BaseSeleniumTest {

    @Test
    public void testAbc() {
        WebDriver driver = getDriver();

        // test stuff
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!