I use selenium-jupiter. I am getting a webdriver from method arguments like this:
@Test
public void testWithChrome(ChromeDriver chromeDriver) {
chromeD
You can do that with WebDriverManager that comes with this extension.
@BeforeEach
public void setUp()
{
switch(browser)
{
case "chrome" ->
{
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
}
case "firefox" ->
{
WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver();
}
case "edge" ->
{
WebDriverManager.edgedriver().setup();
driver = new EdgeDriver();
}
}
driver.manage().window().maximize();
}
In short: When configuring your Selenium extension programmatically you can force usage of a Selenium Grid by configuring its URL as follows (using JUnit 5 annotations):
abstract class UiTest {
@RegisterExtension
static SeleniumExtension seleniumExtension = new SeleniumExtension();
@BeforeAll
static void setUpOnce() {
boolean isRunningInCiEnvironment = ...
if( isRunningInCiEnvironment ) {
// this will force Selenium Jupiter to use a RemoteWebDriver
seleniumExtension.getConfig().setSeleniumServerUrl("http://...");
}
// without above condition, a FirefoxDriver will be used locally
seleniumExtension.addBrowsers(BrowserBuilder.firefox().build(););
}
}
class MyTest extends UiTest {
// Use WebDriver interface in test method: concrete browser detected
// at execution time (via @BeforeAll, inherited from parent class)
@Test
void my_test_Case(WebDriver webDriver) {
webDriver.get(...)
Assert.(...)
}
}
The problem in length is decribed here.
I think what would be better here is to have a method that is executed before any test (annotated with @BeforeAll
) that determines what environment the script is being run in. It probably reads from some config file local vs grid. Once that is determined, assign the driver
variable either an instance of ChromeDriver
or RemoteDriver
. From then on, your tests will pass around the driver
instance which will be of type WebDriver
because both ChromeDriver
and RemoteDriver
inherit from it.
WebDriver driver;
@BeforeAll
public void setup()
{
// read from config file, etc. to determine if local or grid
if (local)
{
driver = new ChromeDriver();
}
else
{
driver = new RemoteDriver();
}
}
@Test
public void test()
{
driver.get("someUrlHere");
}